我用 HTML5 编写了一个代码来将图像加载到画布中。它如下:
<html>
<head>
<script src="jquery-1.9.1.js" ></script>
<script>
window.onload = function ()
{
var canvas1 = document.getElementById("cvs1");
var canvas2 = document.getElementById("cvs2");
var context1 = canvas1.getContext('2d');
var context2 = canvas2.getContext('2d');
var imageXY = {x: 50, y: 50};
// Load the image on canvas1 initially and set the state up with some defaults
state = {}
state.dragging = false;
state.canvas = document.getElementById("cvs2");
state.image = new Image();
state.image.src = 'pick.jpg';
//state.image.id = 'img1';
state.offsetX = 0;
state.offsetY = 0;
state.image.onload = function ()
{
Draw();
}
// This draws the image to the canvas
function Draw ()
{
//Clear both canvas first
context1.clearRect(0,0,canvas1.width,canvas1.height);
context2.clearRect(0,0,canvas2.width,canvas2.height);
//Draw a red rectangle around the image
if (state && state.dragging) {
state.canvas.getContext('2d').strokeStyle = 'red';
state.canvas.getContext('2d').strokeRect(imageXY.x - 2.5,
imageXY.y - 2.5,
state.image.width + 5,
state.image.height + 5);
}
// Now draw the image
state.canvas.getContext('2d').drawImage(state.image, imageXY.x, imageXY.y);
}
}
</script>
<style>
canvas
{
border: 1px solid gray;
}
</style>
<body>
<canvas id="cvs1" width="150" height="600" style="float: left">[No canvas support]</canvas>
<canvas id="cvs2" width="600" height="600" style="float: left; margin-left: 10px">[No canvas support]</canvas>
</body>
</html>
可以如前所述设置状态的属性。但是,我想通过 JQuery 将此图像用于各种事件。我尝试使用“state.image.id = 'img1';” (已评论),但它不起作用。
有人可以帮我将图像的 id 动态添加到画布图像吗?非常感谢。