how to use paperjs on dynamically created canvas?

时光总嘲笑我的痴心妄想 提交于 2019-12-11 23:49:50

问题


I have multiple canvas images on my page I am trying to get canvas id using paperjs after mousedown event on a single image through jquery. My image disappears after a mouse click and after running the below code...

<script type="text/javascript">
 window.onload = function () {

    $('#imgID').on('mousedown', function (e) { //imgID is my div

        if($.isNumeric(e.target.id)){

        console.log(e.target.id);

        var canvas = document.getElementById(e.target.id);
        paper.setup(canvas);
        var path = new paper.Path.Circle({
        center: event.downPoint,
        radius: (event.downPoint - event.point).length,

        strokeColor: 'red'
        });

        // Remove this path on the next drag event:
         path.removeOnDrag();

        }else {
        return;
        }

        var offset = $(this).offset();
        console.log(e.clientX - offset.left);
        console.log(e.clientY - offset.top);
    });
}
</script>

I should be able to draw circles like the one in the below link on multiple images on my website...

http://www.jqueryscript.net/demo/jQuery-Plugin-To-Draw-Shapes-with-Html5-Canvas-Element-drawingshapes/

I cannot use "script type="text/paperscript" canvas=''" as my canvas are created dynamically through javascript. Any help is appreciated. Thanks in advance.


回答1:


If your saying that the element with the id imgID is added dynamically, you'll need to use event delegation like $(document).on('mousedown', '#imgID', function (e) { // your code here...});

<script type="text/javascript">
 window.onload = function () {

    $(document).on('mousedown', '#imgID', function (e) { //imgID is my div

        if($.isNumeric(e.target.id)){

        console.log(e.target.id);

        var canvas = document.getElementById(e.target.id);
        paper.setup(canvas);
        var path = new paper.Path.Circle({
        center: event.downPoint,
        radius: (event.downPoint - event.point).length,

        strokeColor: 'red'
        });

        // Remove this path on the next drag event:
         path.removeOnDrag();

        }else {
        return;
        }

        var offset = $(this).offset();
        console.log(e.clientX - offset.left);
        console.log(e.clientY - offset.top);
    });
}
</script>


来源:https://stackoverflow.com/questions/28932978/how-to-use-paperjs-on-dynamically-created-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!