我是HTML5的新手并尝试使用JCrop裁剪图像。如果我想直接裁剪它没有问题但是当它被绘制到画布时JCrop不起作用。
我认为原因可能是我正在创建一个图像变量,以便能够将其绘制到视口画布并动态设置它的Id。因此Jquery无法访问该动态创建的图像。但即便如此,我也不知道该怎么做。
这是我的完整HTML代码。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>acanimal - Crop image on the client side with JCrop and HTML5 canvas element</title>
<script src="./js/jquery.min.js" type="text/javascript"></script>
<script src="./js/jquery.Jcrop.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="./css/jquery.Jcrop.css" type="text/css" />
<script type="text/javascript">
$(window).load(function () {
var canvas = document.getElementById('viewport'),
context = canvas.getContext('2d');
make_base();
function make_base() {
var base_image = new Image();
base_image.id = 'target';
base_image.src = 'demo_files/sago.jpg';
base_image.onload = function () {
context.drawImage(base_image, 0, 0);
}
}
});
jQuery(function ($) {
$('#target').Jcrop({
onChange: updatePreview,
onSelect: updatePreview,
allowSelect: true,
allowMove: true,
allowResize: true,
aspectRatio: 0
});
function updatePreview(c) {
if (parseInt(c.w) > 0) {
// Show image preview
var imageObj = $("#target")[0];
var canvas = $("#preview")[0];
var context = canvas.getContext("2d");
if (imageObj != null && c.x != 0 && c.y != 0 && c.w != 0 && c.h != 0) {
context.drawImage(imageObj, c.x, c.y, c.w, c.h, 0, 0, canvas.width, canvas.height);
}
}
};
});
</script>
</head>
<body>
<canvas id="viewport" width=602; height=500;></canvas>
<canvas id="preview" style="width:150px;height:150px;overflow:hidden;"></canvas>
</body>
</html>
我做错了什么?
...谢谢