我正在尝试以下代码,以允许我创建图像,允许附加自定义值并在HTML画布上绘制。它似乎似乎没有用。
var canvas = document.getElementById('mainCanvas');
var context = canvas.getContext('2d');
function CreateObject(objectImage){
lastIndex++;
PlanObjects[lastIndex] = new PlanObject(lastIndex,currentSlide,24,24,24,24,objectImage);
context.drawImage(PlanObjects[lastIndex].img,PlanObjects[lastIndex].posX,PlanObjects[lastIndex].posY);
}
var PlanObjects = [];
var lastIndex = -1;
var currentSlide = 0;
function PlanObject(id, slide, width, height, posX, posY, img){
this.id = id;
this.slide = slide;
this.width = width;
this.height = height;
this.posX = posX;
this.posY = posY;
this.img = new Image(img);
}
CreateObject("imgs/icons_star.png");
HTML:
<div id="mainCanvasDiv"><canvas width="800" height="600" id="mainCanvas"></canvas>
我希望创建对象,将其存储在PlanObjects数组中(带有客户值),然后将其绘制到画布上,但似乎不行。
答案 0 :(得分:0)
1)图像构造函数的输入参数为width和height。并且您必须单独设置源:
var myImage = new Image(100, 200);
myImage.src = 'picture.jpg';
document.body.appendChild(myImage);
[https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image]
2)加载图像是异步的,因此您需要处理load
事件:
PlanObjects[lastIndex].img.addEventListener('load', function() {
context.drawImage(PlanObjects[lastIndex].img, PlanObjects[lastIndex].posX, PlanObjects[lastIndex].posY)
});
答案 1 :(得分:0)
我必须修改新的“图像”行以解决问题
var canvas = document.getElementById('mainCanvas');
canvas.width = canvas.scrollWidth;
canvas.height = canvas.scrollHeight;
var context = canvas.getContext('2d');
function CreateObject(objectImage){
lastIndex++;
PlanObjects[lastIndex] = new PlanObject(lastIndex,currentSlide,24,24,24,24,objectImage);
context.drawImage(PlanObjects[lastIndex].img,PlanObjects[lastIndex].posX,PlanObjects[lastIndex].posY);
}
var PlanObjects = [];
var lastIndex = -1;
var currentSlide = 0;
function PlanObject(id, slide, width, height, posX, posY, img){
this.id = id;
this.slide = slide;
this.width = width;
this.height = height;
this.posX = posX;
this.posY = posY;
this.img = new Image();
this.img.src = img;
}
CreateObject("./imgs/icons_star.png");