我试图在每个位置都这样做,我的鼠标会生成一个黑色的圆圈,但我无法让它显示出来,我知道我收到了输入,但我不知道为什么我的东西没出现?是否有某种重复的方法,我错过了?我已经尝试了很多我不太了解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());
});
}
答案 0 :(得分: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
修复了问题。