canvas - Why are images being drawn in the wrong place? -


the following code attempts draw image button selected in toolbar canvas @ mouse position. based on printed coordinates position correctly calculated, images placed in wrong place. code:

import 'dart:html';  class test {   imageelement toolbar_selected_element = null;   canvaselement canvas;   num mousex = null, mousey = null;    void main() {     canvas = query("#canvas");     canvas.onclick.listen(canvas_onclick);      (var toolbutton in queryall('.toolbutton')) {       toolbutton.onclick.listen((e) => toolbar_selected_element = query("#${e.target.id}"));     }   }    void canvas_onclick(mouseevent event) {     num x,y;     var clientboundingrect = canvas.getboundingclientrect();     mousex = event.clientx - clientboundingrect.left;     mousey = event.clienty - clientboundingrect.top;     window.requestanimationframe(draw);   }    void draw(num _) {     canvasrenderingcontext2d context = canvas.context2d;     context.clearrect(0, 0, canvas.width, canvas.height);     if(toolbar_selected_element!= null   && mousex != null && mousey != null) {       print("$mousex $mousey");       context.drawimage(toolbar_selected_element, mousex, mousey);     }   } }  void main() {   new test().main(); } 

the corresponding html file can found at: https://github.com/joaompinto/svgdropper/blob/master/web/svgdropper.html

the issue you're setting css style width , height other canvas's actual width , height. see this answer more details.

if want canonical source of canvas's dimensions in css file, this:

void main() {   canvas = query("#canvas");   canvas.width = int.parse(canvas.getcomputedstyle().width.split('px')[0]);   canvas.height = int.parse(canvas.getcomputedstyle().height.split('px')[0]); 

i hope there's more elegant way strip 'px', that's first thing came mind.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -