2

我正在努力做到这一点,所以在我的鼠标要移动的每个位置都会生成一个黑色圆圈,但我无法让它显示出来,我知道我正在接收输入,但我不知道为什么我的东西不是没有出现?是否有某种我缺少的重绘方法?我已经尝试了很多我不太明白如何requestAnimation在这里工作的东西。

我究竟做错了什么?

import 'dart:html';
import 'dart:async';
import 'package:polymer/polymer.dart';

CanvasElement canvas = document.querySelector('#myPaintCanvas');
CanvasRenderingContext2D context = canvas.getContext('2d');

//circle deminsions
var centerX;
var centerY;
var radius = 15;
var PI = 3.14;

void requestRedraw(){
  window.requestAnimationFrame(scribble());
 }

void scribble(pointX, pointY){
 print("MouseX: " + pointX.toString() + " MouseY: " + pointY.toString());


context.arc(pointX, pointY, radius, 0, 2 * PI, false);
context.fillStyle = 'black';
context.fill();
context.strokeStyle = '#003300';
context.stroke();

}

void main(){
 canvas.onMouseDown.listen((onDown){

    StreamSubscription mouseMoveStream = canvas.onMouseMove.listen((onData){
     scribble(onData.client.x, onData.client.y);
    });

//to end my stream when the mouse is up
canvas.onMouseUp.listen((onData) => mouseMoveStream.cancel());
  });

}
4

1 回答 1

2

由于画布实际绘图尺寸与其作为 DOM 元素 (canvas.width = 500;canvas.style.width="500px";)的尺寸不匹配,您很可能会遇到缩放问题

固定缩放 + 一些额外的修复:

import 'dart:html';
import 'dart:async';

CanvasElement canvas = document.querySelector('#myPaintCanvas');
CanvasRenderingContext2D context;

//circle deminsions
var centerX;
var centerY;
var radius = 15;
var PI = 3.14;


void scribble(pointX, pointY) {
  print("MouseX: " + pointX.toString() + " MouseY: " + pointY.toString());
  context.clearRect(0, 0, canvas.width, canvas.height);
  context.beginPath();
  context.arc(pointX, pointY, radius, 0, 2 * PI, false);
  context.fillStyle = 'black';
  context.fill();
  context.strokeStyle = '#003300';
  context.stroke();
  context.closePath();
}

void main() {
  canvas.width = 500;
  canvas.style.width="500px";
  canvas.height = 500;
  canvas.style.height="500px";
  context = canvas.getContext('2d');
  canvas.onMouseDown.listen((onDown) {

    StreamSubscription mouseMoveStream = canvas.onMouseMove.listen((onData) {
      var rec = canvas.getBoundingClientRect();
      scribble(onData.client.x- rec.left, onData.client.y - rec.top);
    });

    //to end my stream when the mouse is up
    document.onMouseUp.listen((onData) => mouseMoveStream.cancel());
  });
}

我补充 context.clearRect说清楚圆圈在哪里。 context.beginPath();并且 context.closePath(); 需要防止圈子之间的桥梁。当鼠标按钮在画布之外释放时,document.onMouseUp而不是修复问题。canvas.onMouseUp

于 2014-06-20T04:46:17.230 回答