我正在嘗試創建一個也可以放大的平移圖像查看器。如果縮放因子或圖像大小使圖像不再覆蓋整個畫布,我希望畫布區域不包含用指定背景顏色繪製的圖像。畫布上的圖像在平移時留下平鋪痕跡
我目前的實現允許縮放和平移,但會產生不希望的效果,即在平移操作期間圖像留下平鋪痕跡(很像當您贏得遊戲時在Windows紙牌中顯示的紙牌)。如何清理畫布,使圖像不會留下痕跡,並且我的背景矩形可以在畫布中正確呈現?
重新創建不需要的效果設置放大到某個級別,在該級別您將看到深灰色背景顯示,然後用鼠標平移圖像(鼠標向下並拖動)。
下面添加的代碼片段和Plnkr鏈接爲那些誰想要在那裏搞砸。 http://plnkr.co/edit/Cl4T4d13AgPpaDFzhsq1
<!DOCTYPE html>
<html>
<head>
<style>
canvas{
border:solid 5px #333;
}
</style>
</head>
<body>
\t <button onclick="changeScale(0.10)">+</button>
\t <button onclick="changeScale(-0.10)">-</button>
\t
<div id="container">
<canvas width="700" height="500" id ="canvas1"></canvas>
</div>
<script>
var canvas = document.getElementById('canvas1');
var context = canvas.getContext("2d");
var imageDimensions ={width:0,height:0};
var photo = new Image();
var isDown = false;
var startCoords = [];
var last = [0, 0];
var windowWidth = canvas.width;
var windowHeight = canvas.height;
var scale=1;
photo.addEventListener('load', eventPhotoLoaded , false);
photo.src = "http://www.html5rocks.com/static/images/cors_server_flowchart.png";
function eventPhotoLoaded(e) {
imageDimensions.width = photo.width;
imageDimensions.height = photo.height;
drawScreen();
}
function changeScale(delta){
scale += delta;
drawScreen();
}
function drawScreen(){
context.fillRect(0,0, windowWidth, windowHeight);
context.fillStyle="#333333";
context.drawImage(photo,0,0,imageDimensions.width*scale,imageDimensions.height*scale);
}
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]);
drawScreen();
}
</script>
</body>
</html>
也許像'context.save(); context.fillRect(0,0,windowWidth,windowHeight); context.restore();'因爲setTransform也改變了你填充的矩形。 – Quarter2Twelve
你是對的。如果你想發表評論作爲答案,我會很樂意接受它。 – mccainz