我有一个图像,我想在它上面画一些正方形。但我在 getContext('2d')
上不断收到未定义的函数。我必须补充一点,var img 是已经加载到页面上的图像,我试图将其解释为 Canvas ,因为我正在使用另一个脚本,该脚本允许选择图像上的区域,如果我使用 Canvas ,则脚本不管用。那么,如果我无法将图像解释为 Canvas ,您有何建议?
Js函数
function drawInput(dx1,dy1,dx2,dy2) {
var img = document.getElementById('home:tempImg');
var canvas = img;
console.log(canvas);
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, dx1, dy1,dx2-dx1,dy2-dy1);
};
imageObj.src = 'images/selected.png';
}
HTML
<h:body>
<h:form onsubmit="#{getComponents.getAllComponents()}" id="home">
<div>
<p:graphicImage id="tempImg" rendered="true" value="#{imageView.selectedImg}">
</p:graphicImage>
</div>
</h:form>
</h:body>
<script type="text/javascript">
var myJSONStr ='{ "area" : #{areaInputView.areaListString}}';
console.log(myJSONStr);
var json = JSON.parse(myJSONStr);
//console.log(json.area[1].x1);
for(var i=0;myJSONStr.length >i ; i++) {
console.log(json.area[i].x1, json.area[i].y1, json.area[i].x2, json.area[i].y2);
drawInput(json.area[i].x1, json.area[i].y1, json.area[i].x2, json.area[i].y2);
};
</script>
</html>
最佳答案
通过利用自定义 JS“类”(在本例中为 app.Image
类型),我们可以构建一个非常简洁的包装器,它允许我们根据我们保留的其他实例动态绘制图像踪迹。
查看 this Codepen 一个工作示例。
window.app = window.app || {};
app.Canvas = document.getElementById('myCanvas').getContext('2d');
app.Image = function(source, x, y) {
this.x = x;
this.y = y;
this.data = new Image();
this.data.addEventListener('load', this.draw.bind(this));
this.data.src = source;
};
app.Image.prototype.draw = function() {
app.Canvas.drawImage(this.data, this.x, this.y);
};
app.Image.prototype.getImageBounds = function() {
return {
height: this.data.height,
width: this.data.width
}
};
var myImage = new app.Image('http://placehold.it/250x250', 10, 10);
var mySecondImage = new app.Image('http://placesheen.com/100/100', myImage.x + 10, myImage.y + 10);
最重要的一行是最后一行。请注意,我们如何使用相对于第一张图像的 x
和 y
坐标来初始化新的 app.Image
。通过使用跟踪这些信息的自定义包装类,我们能够轻松访问在各种情况下所需的必要数据。
我希望这有助于您走上正轨!如果您对代码有任何疑问,请告诉我,我很乐意解释。
关于javascript - 使用图像代替 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27153053/