0
我能夠處理一個圖像,能夠平滑地縮放和平移,並且能夠繪製該圖像的形狀。如何在畫布上繪製多個圖像?
在畫布上繪製兩幅圖像。但是當我縮放它時,Chrome會崩潰。
gkhead.jpg是主要圖像,並在此圖像上繪製alphaball.png圖像。
window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded() {
canvasApp();
}
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext('2d');
function canvasApp(){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext('2d');
eventShipLoaded();
function eventShipLoaded() {
draw1(scaleValue);
}
function draw1(scaleValue){
var tileSheet = new Image();
tileSheet.addEventListener('load', eventShipLoaded , false);
tileSheet.src = "gkhead.jpg";
var tileSheet1 = new Image();
tileSheet1.addEventListener('load', eventShipLoaded , false);
tileSheet1.src = "alphaball.png";
var x = 0;
var y = 0;
var width = 480;
var height = 480;
context.save();
context.setTransform(1,0,0,1,0,0)
context.globalAlpha = 0.5;
//context.drawImage(tileSheet,x,y, width, height);
context.clearRect(0, 0, canvas.width, canvas.height);
context.restore();
//drawBoard();
context.save();
context.drawImage(tileSheet, x, y, tileSheet.width*scaleValue, tileSheet.height*scaleValue);
context.scale(scaleValue, scaleValue);
context.drawImage(tileSheet1, 200, 200, 40/scaleValue, 40/scaleValue);
context.restore();
/*context.globalAlpha = 0.5;
context.fillStyle = "blue";
context.fillRect(180, 180, 40/scaleValue, 40/scaleValue);
context.fillRect(260, 190, 40/scaleValue, 40/scaleValue);*/
};
var scaleValue = 1;
var scaleMultiplier = 0.8;
var startDragOffset = {};
var mouseDown = false;
// add button event listeners
document.getElementById("plus").addEventListener("click", function(){
scaleValue /= scaleMultiplier;
draw1(scaleValue);
//eventShipLoaded();
}, false);
document.getElementById("minus").addEventListener("click", function(){
scaleValue *= scaleMultiplier;
//draw1(scaleValue);
eventShipLoaded();
}, false);
document.getElementById("original_size").addEventListener("click", function(){
scaleValue = 1;
//draw1(scaleValue);
eventShipLoaded();
}, false);
var isDown = false;
var startCoords = [];
var last = [0, 0];
canvas.onmousedown = function(e){
isDown = true;
startCoords = [
e.offsetX - last[0],
e.offsetY - last[1]
];
};
canvas.onmouseup = function(e){
isDown = false;
last = [
e.offsetX - startCoords[0], // set last coordinates
e.offsetY - startCoords[1]
];
};
canvas.onmousemove = function(e){
if(!isDown) return;
var x = e.offsetX;
var y = e.offsetY;
context.setTransform(1, 0, 0, 1, x - startCoords[0], y - startCoords[1]);
//draw1(scaleValue);
eventShipLoaded();
}
}
請放上您的代碼或代碼段。 –
@NK:用我的代碼更新了問題。請看看 –