logo
down
shadow

Overcoming antialiasing on canvas lines for mouse event


Overcoming antialiasing on canvas lines for mouse event

By : Diego Alejandro Faja
Date : November 21 2020, 03:00 PM
fixed the issue. Will look into that further You can draw such a pixelated shape on canvas by using SVG filter which removes alpha values of shape edge. (But SVG filter is a bit heavy.)
code :
const ctx = canvas.getContext("2d");

//normal line(antialiased)
ctx.moveTo(20,20); ctx.lineTo(180,20);
ctx.stroke();

//set "crisp edge" filter
ctx.filter = "url(#crisp)";
//crisp line
ctx.beginPath();ctx.moveTo(20,40); ctx.lineTo(180,40);
ctx.moveTo(20, 50); ctx.lineTo(180, 70);
//crisp circle
ctx.moveTo(150, 130); ctx.arc(100, 130, 50, 0, Math.PI*2);
ctx.stroke();
<canvas id="canvas" width="200" height="200"></canvas>
<svg style="visibility:hidden;width:0;height:0;">
  <defs>
    <!--SVG filter to remove alpha-->
    <filter id="crisp">
      <feComponentTransfer>
        <feFuncA type="discrete" tableValues="0,1"></feFuncA>
      </feComponentTransfer>
    </filter>
  </defs>
</svg>
const ctx = canvas.getContext("2d");

//temporary canvas to removeAlpha
const tmp = document.createElement("canvas");
[tmp.width, tmp.height] = [canvas.width, canvas.height];
const tctx = tmp.getContext("2d");

//normal line(antialiased)
ctx.moveTo(20,20); ctx.lineTo(180,20);
ctx.stroke();

//crisp line
tctx.beginPath(); tctx.moveTo(20,40); tctx.lineTo(180,40);
tctx.moveTo(20, 50); tctx.lineTo(180, 70);
removeAlpha();

//crisp circle
tctx.moveTo(150, 130); tctx.arc(100, 130, 50, 0, Math.PI*2);
tctx.stroke();
removeAlpha();

//remove alpha on tmp canvas and draw it to main canvas.
function removeAlpha(){
  const threshold = 128;//you can change the value
  const id = tctx.getImageData(0, 0, tmp.width, tmp.height);
  const data = id.data;//pixel data array
  //remove alpha values pixel by pixel.
  for(let i = 0, len = canvas.width * canvas.height; i<len; i++){
    const apos = i * 4 + 3;//alpha data position
    const a = data[apos];
    data[apos] = a > threshold ? 255 : 0;
  }
  tctx.putImageData(id, 0, 0);
  ctx.drawImage(tmp, 0, 0);
  tctx.clearRect(0, 0, tmp.width, tmp.height);
}
<canvas id="canvas" width="200" height="200"></canvas>


Share : facebook icon twitter icon
HTML5 Canvas mouse over event on canvas

HTML5 Canvas mouse over event on canvas


By : Gerard
Date : March 29 2020, 07:55 AM
wish help you to fix your issue You need to use javascript to create a mouseover event...check out this example
code :
function RefreshMouseEvents( ElementId ) 
{
    FireEvent( ElementId, 'mouseover' );
    setTimeout( "TriggerMouseEvent( '" + ElementId + "', '" + event.clientX + "', '" + event.clientY + "' )", 1 );
}

function TriggerMouseEvent( ElementId, MouseXPos, MouseYPos )
{
    if( IsMouseOver( ElementId, (1*MouseXPos), (1*MouseYPos) ) )
        FireEvent( ElementId, 'mouseover' );
    else    
        FireEvent( ElementId, 'mouseout' );
}

function IsMouseOver( ElementId, MouseXPos, MouseYPos )
{
    if( document.getElementById(ElementId) != null )    
    {
        var Element = document.getElementById(ElementId);   
        var Left  = Element.getBoundingClientRect().left, 
            Top   = Element.getBoundingClientRect().top,
            Right = Element.getBoundingClientRect().right,
            Bottom  = Element.getBoundingClientRect().bottom;       
        return ( (MouseXPos >= Left) && (MouseXPos <= Right) && (MouseYPos >= Top) && (MouseYPos <= Bottom))    
    }
    else
        return false;
}

function FireEvent( ElementId, EventName )
{
    if( document.getElementById(ElementId) != null )    
    {   
        if( document.getElementById( ElementId ).fireEvent ) 
        {
            document.getElementById( ElementId ).fireEvent( 'on' + EventName );     
        }
        else 
        {   
            var evObj = document.createEvent( 'Events' );
            evObj.initEvent( EventName, true, false );
            document.getElementById( ElementId ).dispatchEvent( evObj );
        }
    }
}
Drawing lines with opacity on a canvas with the mouse

Drawing lines with opacity on a canvas with the mouse


By : Trololinlo
Date : March 29 2020, 07:55 AM
I hope this helps you . There's a question very similar to mine here. The reason I'm posting this is because half the question in the link was never answered. I'm at the point where the line is consistent all the way through, but you can't see what you're doing while drawing. The code went something like this: , Here is code with kinetic.js :
Html :
code :
<html>
  <head>
    <META http-equiv="Content-Type" content="text/html; charset=utf-16">
    <script src="jquery-2.0.3.js" type="text/javascript"></script>
    <script src="cn.js" type="text/javascript"></script>
    <script src="kinetic.js" type="text/javascript"></script>
    <style>  
  </style>
</head>
<body>
<div id="container"  height="300px" style="width:300px;height:300px;border:3px solid"></div>
</body>
</html>
$(function()
{

    var lineSx,lineSy,lineFx,lineFy;
    var ismouseDown=false;
    var line;
    var layerList=new Array();


    setInterval(function(){// for clearing the temp layer 

        var l=null,topLayer;
        var i=1;
        l=layerList.pop();      
        while(l){
            //console.log(l);
            if(i!=1){
                l.destroy();
                l=null; 
            }
            else{
                topLayer=l;
            }           
            l=layerList.pop();
            i++;
        }
        layerList.push(topLayer);

    },2);

    var stage = new Kinetic.Stage({
        container: 'container',
        width: 300,
        height: 300
      });
      var layer = new Kinetic.Layer();


      var rect = new Kinetic.Rect({
        x: 0,
        y: 0,
        width: 300,
        height: 300,
        fill: 'black',        
      });    
    rect.on("mousedown",function(e){

        console.log(e);
        ismouseDown=true;
        lineSx=e.clientX;   
        lineSy=e.clientY;   
    });
    rect.on("mousemove",function(e){

        if(ismouseDown){

            console.log(e);
            var cx=e.clientX;   
            var cy=e.clientY;

            var tempLayer = new Kinetic.Layer();

            //stage.remove(tempLayer);
            line=createLine(lineSx,lineSy,cx,cy);
            tempLayer.add(line);
            stage.add(tempLayer);       
            layerList.push(tempLayer);                      
        }

    });
    rect.on("mouseup",function(e){
        ismouseDown=false;
        console.log(e);
        lineFx=e.clientX;   
        lineFy=e.clientY;

        line=createLine(lineSx,lineSy,lineFx,lineFy);
        layer.add(line);
         stage.add(layer);  
    });

    layer.add(rect);    
    stage.add(layer);


});
function createLine(sx,sy,fx,fy){
    var line = new Kinetic.Line({
        points: [sx,sy,fx,fy],
        stroke: 'white',
        strokeWidth: 3,
        lineCap: 'round',
        lineJoin: 'round'
     });
     return line;

}
Antialiasing when drawing lines in Canvas in Firefox

Antialiasing when drawing lines in Canvas in Firefox


By : RonenHa
Date : March 29 2020, 07:55 AM
may help you . It looks like you're slightly zoomed-in on Firefox (notice how the lines are spaced slightly further apart)
Hit Ctrl+0 to reset the zoom level. This should fix your problem.
C# - WPF - Mousemove event on canvas will overload the mouse events so click event is not fired

C# - WPF - Mousemove event on canvas will overload the mouse events so click event is not fired


By : user2777516
Date : March 29 2020, 07:55 AM
This might help you Here's a minimal code sample which works properly and does not have the problem you mention: it can add shapes as fast as I can click. I suggest you inspect the differences with your code to find the culprit - for one, I don't continuously call updateCanvas or similar as this is not needed.
xaml:
code :
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" SizeToContent="WidthAndHeight">
  <Canvas x:Name="canvas" Background="AntiqueWhite" Width="1024" Height="768"
          MouseMove="Canvas_MouseMove" MouseDown="Canvas_MouseDown" />
</Window>
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

namespace WpfApplication1
{
  public class Item
  {
    private readonly Rectangle shape;

    public Item( Canvas canvas )
    {
      shape = new Rectangle { Width = 50, Height = 50, Fill = Brushes.Black };
      canvas.Children.Add( shape );
      SetPosition( 0.0, 0.0 );
    }

    public void SetPosition( double x, double y )
    {
      Canvas.SetLeft( shape, x );
      Canvas.SetTop( shape, y );
    }
  }

  public partial class MainWindow : Window
  {
    private readonly IList<Item> shapes;
    private Item currentMovingShape;

    public MainWindow()
    {
      InitializeComponent();
      shapes = new List<Item>();
      InitMovingShape();
    }

    private void InitMovingShape()
    {
      currentMovingShape = new Item( canvas );
    }

    private void SetMovingShapePosition( MouseEventArgs e )
    {
      var pos = e.GetPosition( canvas );
      currentMovingShape.SetPosition( pos.X, pos.Y );
    }

    private void Canvas_MouseMove( object sender, MouseEventArgs e )
    {
      SetMovingShapePosition( e );
    }

    private void Canvas_MouseDown( object sender, MouseButtonEventArgs e )
    {
      shapes.Add( currentMovingShape );
      InitMovingShape();
      SetMovingShapePosition( e );
    }
  }
}
Fast drawing lots of lines in Android Canvas: dealing with antialiasing and KitKat's peculiarities

Fast drawing lots of lines in Android Canvas: dealing with antialiasing and KitKat's peculiarities


By : Jim Curran
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Well, the solution is just the result of what was written in chat (see Colt's post):
1) The original input array is split into pieces containing no NaNs
Related Posts Related Posts :
  • How to get text from selected value in a dropdownlist which is js based
  • window is not defined angular universal third library
  • Angularjs ng-repeat stylization depending on previous value
  • Trying to implement Fittext.js
  • Calculate number of match in array Lodash
  • Jquery Smooth Scroll Using Offset.top
  • How to extract data to React state from CSV file using Papa Parse?
  • How to add unique links to google maps markers
  • How to use if condition in a tool bar in java script
  • Ajax filter in django not showing in HTML
  • data collection with Javascript
  • Rotate image on lightbox2 load
  • Prevent body from scrolling when a Pop-Up is open
  • How to copy files that do not need to be compiled in Gulp?
  • Array not assigned to variable? How does this work and what exactly is it doing?
  • Sorting associative array of objects in javascript
  • Changing Icon in Sap.m.tree having CustomTreeItem
  • Merge two array of objects based on a key
  • javascript in css not working
  • Passing only clicked element to onClick function - reactjs
  • React boilerplate doesn't load js files in the index.html
  • is Child service inside child component visible in the Parent component?
  • Check if data attribute value equals a string
  • How to get value of child tag of a button tag
  • How to access subjects of selected mails in Apple Mail using JavaScript?
  • How to get all dynamically set inline-style CSS in jQuery?
  • Error: Module "html" does not provide a view engine (Express)
  • Random Image in <Div> from array
  • Slider with touch function
  • ReactJS Component Architecture Problems / Nested Components or Single Component Manager
  • Javascript: Caching within Closure doesn't work
  • HTM5 Canvas Drawing App: How Do I Select The Color?
  • Assigning Events using HTML DOM
  • html5 getUserMedia() portrait mode
  • How to avoid 'headers already sent' within Promise chain?
  • Get a result from a react native app integrated into an existing android app
  • Why does the value of input field return undefined
  • How to get return object in jquery uploadFile method
  • Javascript string with arguments to single quotes
  • Understanding JS functions syntax (applies to other languages as well, I'm sure)
  • AngularJS Single Page App: Reference Error, ____ is not defined
  • whatwg-fetch new typescript 2.5.3
  • React.js - Array.unshift() not updating array on front-end
  • JavaScript localeCompare don't sort well [ "aaa-1.0", "aaa-1.1", "aaa-1.01", "aaa-11&
  • Mongoose handle validation error in a promise call and Express middleware
  • Building tree array of objects from flat array of objects
  • How to add a progress bar to file upload using javascript and ajax call?
  • JavaScript: is it permitted to override a standard built-in object?
  • Change the current page of an AJAX datatables
  • Array element is undefined even after pushing elements into it
  • onmousemove event not working
  • Chrome-Extension/JavaScript How to make all links on page have no effect?
  • Websocket issue Internet Explorer
  • sessionStorage value becomes null in other tab in AngularJS
  • Split URL from position x to the end in Javascript
  • How to set value of input field with NgIf in Angular 4
  • invalidStateError for second time screenshare on Chrome
  • How do you pass a value to the variable in a xhr.setRequestHeader?
  • I cant start nodemon on my windows 10
  • Nested if else jumps out from the main if else in javascript
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org