代码之家  ›  专栏  ›  技术社区  ›  SystemX17

如何使用Javascript在画布上创建和绘制图像数组?

  •  0
  • SystemX17  · 技术社区  · 6 年前

    我正在尝试以下代码,以允许我创建一个图像,允许附加自定义值并在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数组中(带有它的客户值),并将其绘制到画布上,但它似乎没有做到这一点。

    2 回复  |  直到 6 年前
        1
  •  0
  •   stdob--    6 年前

    1)图像构造器的输入参数是宽度和高度。必须分别设置源:

    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)
    });
    

    [ https://developer.mozilla.org/en-US/docs/Web/Events/load ]

    [ https://jsfiddle.net/bvupyroc/ ]

        2
  •  0
  •   SystemX17    6 年前

    我不得不修改新的图像行来解决这个问题

    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");