我需要一个程序,允许用户剪切带有矩形的图像:
https://jsfiddle.net/w3qfLr10/58/
我预计当我点击画布上的不同位置时,程序会在该位置剪切背景图像。但是,正如您从链接中看到的,每次单击鼠标时,屏幕都不会刷新。我预计背景只会在最新的鼠标位置被一个矩形剪掉;相反,似乎所有鼠标点击都会剪切背景。Thanks
这是我的代码:
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id='myCanvas' width="480" height="320"> </canvas>
<script >
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
var rectX = 75;
var rectY = 60;
function draw() {
context.clearRect(0,0, canvas.width, canvas.height);
context.beginPath();
context.rect(rectX, rectY, 250, 180);
context.clip();
context.drawImage(imageObj, 69, 50);
};
imageObj.onload = function() {
draw();
canvas.onmouseup = function(e) {
rectX = e.x;
rectY = e.y;
draw();
};
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
</script>
</body>
</html>
答案 0 :(得分:0)
我弄清楚出了什么问题。为了使程序的行为符合我的预期,我只需要在路径之前添加context.save(),在绘图之后添加context.restore()。所以,新代码看起来像这样:
....
context.clearRect(0,0, canvas.width, canvas.height);
context.save(); //new code
context.beginPath();
context.rect(rectX, rectY, 250, 180);
context.clip();
context.drawImage(imageObj, 69, 50);
context.restore();//new code