1 回答
TA贡献1829条经验 获得超7个赞
干得好。我稍微编辑了你的代码。
<html>
<head>
</head>
<body onLoad="init();">
<script>
var context;
var x=100;
var y=100;
var dx=5;
var dy=2;
var image;
var image_height = 100;
var image_width = 100;
var myCanvas;
function init()
{
myCanvas = document.getElementById("myCanvas");
context= myCanvas.getContext('2d');
image = new Image();
image.onload = function() {
context.drawImage(image, x,y, image_width, image_height);
}
image.src="https://img.icons8.com/ios/452/dvd-logo.png";
setInterval(draw,20);
}
function draw()
{
context.clearRect(0,0, 600,600);
context.drawImage(image, x,y, 100, 100);
context.globalCompositeOperation = "source-in";
// draw color
var right_bound = 600 - image_width;
var bottom_bound = 600 - image_height;
// Boundary Logic
if (x < 0 || x > right_bound){
dx = -dx;
context.fillStyle = "#09f";
}
if (y < 0 || y > bottom_bound){
dy = -dy;
context.fillStyle = "#ff0";
}
context.fillRect(0, 0, 600, 600);
//reset back to default global composite
context.globalCompositeOperation = "source-over";
x+=dx;
y+=dy;
}
</script>
<canvas id="myCanvas" width="600" height="600"> </canvas>
</body>
</html>
添加回答
举报