绘制图像需要什么?

时间:2013-04-19 16:23:37

标签: dart drawimage

以下代码应在鼠标在工具栏中选择后在画布中移动时绘制图像:

import 'dart:html';


    class Test {
      ImageElement toolbar_selected_element = new ImageElement();
      CanvasElement canvas;
      var loaded_image_toolbar = false;
      var mouseX = null, mouseY = null;

      void main() {
        canvas = query("#canvas");
        canvas.onMouseMove.listen(canvas_OnMouseMove);
        query(".toolbuton").onDragStart.listen(toolbar_button_OnClick);
      }

      void toolbar_button_OnClick(MouseEvent event) {
        toolbar_selected_element.onLoad.listen(tool_button_image_OnLoad);
        toolbar_selected_element.src = event.target.src;
       }

      void tool_button_image_OnLoad(event) {
        loaded_image_toolbar = true;
        window.requestAnimationFrame(draw);
      }

      void canvas_OnMouseMove(MouseEvent event) {
        mouseX = event.clientX;
        mouseY = event.clientY;
        window.requestAnimationFrame(draw);
      }

      void draw(num _) {
        if(loaded_image_toolbar && mouseX != null && mouseY != null) {
          CanvasRenderingContext2D context = canvas.context2d;
          context.drawImage(toolbar_selected_element, mouseX, mouseY);
        }
      }
    }

    void main() {
      new Test().main();
    }

调用draw方法但是图片没有在画布中显示,缺少什么?

1 个答案:

答案 0 :(得分:3)

我猜测元素类实际上是toolbutton而不是toolbuton

你的Dart代码(或多或少)适用于我这样的HTML正文:

<body>
  <canvas id="canvas"></canvas>
  <img class="toolbuton" src="./test.png" />
</body>

当然,既然你想在不同的图像之间进行选择(我认为......),这更像是:

<body>
  <canvas id="canvas"></canvas>
  <img class="toolbutton" src="./test.png" />
  <img class="toolbutton" src="./test2.png" />
</body>

然后在Test.main()中为每个工具按钮添加一个监听器,而不仅仅是第一个:

for (var toolbutton in queryAll('.toolbutton')) {
  toolbutton.onClick.listen(toolbar_button_OnClick);
}

然后我点击任一图像并将其绘制在画布中的光标位置,我可以在它们之间来回切换,我相信这就是你想要的。