Showing posts with label canvas. Show all posts
Showing posts with label canvas. Show all posts

Friday, July 27, 2018

CORS policy on cached Image

Leave a Comment

In chrome 22 & safari 6.

Loading images from s3 for usage in a canvas (with extraction as a primary intent) using a CORS enabled S3 bucket, with the following code:

<!-- In the html --> <img src="http://s3....../bob.jpg" />   // In the javascript, executed after the dom is rendered this.img = new Image(); this.img.crossOrigin = 'anonymous'; this.img.src = "http://s3....../bob.jpg"; 

I have observed the following:

  1. Disable caches
  2. Everything works fine, both images load

Then trying it with caches enabled:

  1. Enable caches
  2. DOM image loads, canvas image creates a dom security exception

If I modify the javascript portion of the code to append a query string, like so:

this.img = new Image(); this.img.crossOrigin = 'anonymous'; this.img.src = "http://s3....../bob.jpg?_"; 

Everything works, even with caching enabled fully. I got on to the caching being a problem by using an http proxy and observing that in the failure case, the image isn't actually being requested from the server.

The conclusion I'm forced to draw is that the image cache is saving the original request headers, which are then being used for the subsequent CORS enabled request - and the security exception is being generated due to violation of the same origin policy.

Is this intended behavior?

Edit: Works in firefox.

Edit2: Cors policy on s3 bucket

<?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">     <CORSRule>         <AllowedOrigin>*</AllowedOrigin>         <AllowedMethod>GET</AllowedMethod>     </CORSRule> </CORSConfiguration> 

I'm using wide open because I'm just testing from my local box right now. This isn't in production yet.

Edit3: Updated cors policy to specify an origin

<?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">     <CORSRule>         <AllowedOrigin>http://localhost:5000</AllowedOrigin>         <AllowedMethod>GET</AllowedMethod>     </CORSRule> </CORSConfiguration> 

Verified outgoing headers:

Origin  http://localhost:5000 Accept  */* Referer http://localhost:5000/builder Accept-Encoding gzip,deflate,sdch Accept-Language en-US,en;q=0.8 Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.3 

Incoming headers:

Access-Control-Allow-Origin http://localhost:5000 Access-Control-Allow-Methods    GET Access-Control-Allow-Credentials    true 

Still fails in chrome if I don't bust the cache when loading into the canvas.

Edit 4:

Just noticed this in the failure case.

Outgoing headers:

GET /373c88b12c7ba7c513081c333d914e8cbd2cf318b713d5fb993ec1e7 HTTP/1.1 Host    amir.s3.amazonaws.com User-Agent  Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.91 Safari/537.4 Accept  */* Referer http://localhost:5000/builder Accept-Encoding gzip,deflate,sdch Accept-Language en-US,en;q=0.8 Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.3 If-None-Match   "99c958e2196c60aa8db385b4be562a92" If-Modified-Since   Sat, 29 Sep 2012 13:53:34 GMT 

Incoming headers:

HTTP/1.1 304 Not Modified x-amz-id-2  3bzllzox/vZPGSn45Y21/vh1Gm/GiCEoIWdDxbhlfXAD7kWIhMKqiSEVG/Q5HqQi x-amz-request-id    48DBC4559B5B840D Date    Sat, 29 Sep 2012 13:55:21 GMT Last-Modified   Sat, 29 Sep 2012 13:53:34 GMT ETag    "99c958e2196c60aa8db385b4be562a92" Server  AmazonS3 

I think this is the first request, triggered by the dom. I don't know that it isn't the javascript request though.

3 Answers

Answers 1

The problem is that the image is cached from a former request, without the required CORS headers.Thus, when you ask for it again, for the canvas, with the 'crossorigin' specified, the browser uses the cached version, doesn't see the necessary headers, and raises a CORS error. When you add the '?_' to the url, the browser ignores the cache, as this is another URL. Take a look at this thread: https://bugs.chromium.org/p/chromium/issues/detail?id=409090

Firefox and other browsers do no have that problem.

Answers 2

What CORS settings are you applying? This post suggests that wildcards in AllowedOrigin are parsed (rather then being sent verbatim, this appears to be undocumented behaviour); and the Access-Control-Allow-Origin header value is then cached for subsequent requests, causing issues similar to what you're reporting.

Answers 3

I had a very similar problem and solved it by adding the following header to the response from the server.

'Vary': 'Origin' 

After adding the header all my requests got cached.

Read More

Friday, May 18, 2018

Change dimension of canvas depending on selected option

Leave a Comment

I was working on canvas and came across the Idea of changing dimensions of the cube. So, by using HTML5 Canvas I made up this cube which has two squares joined by the lines to make it look like a cube.

What I want is when I select a cube type from select the cube should automatically change itself depending on the length and width of the selected option. The height remains constant. Like if the I select the cube of 5x5 which is by default a cube but when the I select the option of 5x10 the width(front) should not be changed but the length(side) of the cube should expand, and vice versa if I select 10x5 my max option is 25x15. As you can see the canvas I created below is in pixels, first I need to convert these pixels into centimeters(cm) then centimeters to cubic meters.

The whole cube should be aligned in the fixed canvas area specified.

Here is fiddle

var canvas = document.querySelector('canvas');    canvas.width = 500;  canvas.height = 300;    var contxt = canvas.getContext('2d');    //squares  /*  contxt.fillRect(x, y, widht, height);  */  contxt.strokeStyle = 'grey';  var fillRect = false;  contxt.fillStyle = 'rgba(0, 0, 0, 0.2)';  contxt.rect(80, 80, 100, 100);  contxt.rect(120, 40, 100, 100);  if (fillRect) {    contxt.fill();  }  contxt.stroke();    /*Lines  contxt.beginPath();  contxt.moveTo(x, y);  contxt.lineTo(300, 100);  */  contxt.beginPath();    contxt.moveTo(80, 80);  contxt.lineTo(120, 40);    contxt.moveTo(180, 80);  contxt.lineTo(220, 40);    contxt.moveTo(80, 180);  contxt.lineTo(120, 140);    contxt.moveTo(180, 180);  contxt.lineTo(220, 140);    contxt.stroke();
canvas {    border: 1px solid #000;  }  select {    display: block;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <select>    <option>5x5</option>    <option>5x10</option>    <option>10x5</option>  </select>    <canvas></canvas>

2 Answers

Answers 1

Drawing the cube:

To generate a dynamic cube you would have to listen to an onChange event on the <select> element. Every time the selected option changes you would want to redraw your cube.

To redraw the cube you need to create a renderCube function which should take the new dimensions of the cube and as specified an offset for positioning. In this function you have to clear the previously drawn cube and redraw the new one with the given dimensions and offset.

Adding a transition effect:

As you can not apply css transitions to canvas elements you have to implement the transition yourself. You would have to create an animation function which would calculate the dimensions of the cube in the transition phase and rerender it to the screen on each frame.

An implementation of the resizable cube with a transition effect would be:
(if you prefer here is a fiddle too)
(if you do not need the transition effect check the fiddle before it has been implemented)

var canvas = document.querySelector('canvas');  canvas.width = 320;  canvas.height = 150;  var contxt = canvas.getContext('2d');    var currentHeight = 0, currentWidth = 0, currentDepth = 0, animationId = 0;    function renderCube(height, width, depth, offsetX, offsetY) {    currentHeight = height;    currentWidth = width;    currentDepth = depth;      // Clear possible existing cube    contxt.clearRect(0, 0, canvas.width, canvas.height);    contxt.beginPath();      // Calculate depth, width and height based on given input    depth = (depth * 10 * 0.8) / 2;    width = width * 10;    height = height * 10;      // Draw 2 squares to the canvas    contxt.strokeStyle = 'grey';    var fillRect = false;    contxt.fillStyle = 'rgba(0, 0, 0, 0.2)';    contxt.rect(offsetX, offsetY, width, height);    contxt.rect(offsetX + depth, offsetY - depth, width, height);    if (fillRect) {      contxt.fill();    }    contxt.stroke();        // An array which specifies where to draw the depth lines between the 2 rects    // The offset will be applied while drawing the lines    var depthLineCoordinates = [      // posX, posY, posX2, posY2      [0, 0, depth, -depth],      [width, 0, width + depth, -depth],      [0, height, depth, height - depth],      [width, height, width + depth, height - depth]    ];      // Draw the depth lines to the canvas    depthLineCoordinates.forEach(function(element) {      contxt.moveTo(offsetX + element[0], offsetY + element[1]);      contxt.lineTo(offsetX + element[2], offsetY + element[3]);    });    contxt.stroke();  }    // As requested by OP an example of a transition to the cube  // The transitionDuration may be a double which specifies the transition duration in seconds  function renderCubeWithTransistion(height, width, depth, offsetX, offsetY, transitionDuration) {    var fps = 60;    var then = Date.now();    var startTime = then;    var finished = false;      var heightDifference = (height - currentHeight);    var widthDifference = (width - currentWidth);    var depthDifference = (depth - currentDepth);      // Get an "id" for the current animation to prevent multiple animations from running at the same time.    // Only the last recently started animation will be executed.    // If a new one should be run, the last one will get aborted.    var transitionStartMillis = (new Date()).getMilliseconds();    animationId = transitionStartMillis;      function animate() {      // Do not continue rendering the current animation if a new one has been started      if (transitionStartMillis != animationId) return;      // request another frame if animation has not been finished      if (!finished) requestAnimationFrame(animate);        // Control FPS      now = Date.now();      elapsed = now - then;        if (elapsed > (1000 / fps)) {        then = now - (elapsed % (1000 / fps));          // Calculate a linear transition effect        if (parseInt(currentHeight, 0) != parseInt(height, 0)) currentHeight += heightDifference / (transitionDuration * fps);        if (parseInt(currentWidth, 0) != parseInt(width, 0)) currentWidth += widthDifference / (transitionDuration * fps);        if (parseInt(currentDepth, 0) != parseInt(depth, 0)) currentDepth += depthDifference / (transitionDuration * fps);          // Render the cube        renderCube(currentHeight, currentWidth, currentDepth, offsetX, offsetY);          // Check if the current dimensions of the cube are equal to the specified dimensions of the cube        // If they are the same, finish the transition        if (parseInt(currentHeight, 0) === parseInt(height, 0) && parseInt(currentWidth, 0) === parseInt(width, 0) && parseInt(currentDepth, 0) === parseInt(depth, 0)) {          finished = true;        }      }    }      // Start the animation process    animate();      return true;  }    // Draw the cube initially with 5x5  renderCube(5, 5, 5, 80, 70);    // Add the onChange event listener to the select element  var cubeSizeSelector = document.getElementById('cubeSizeSelector');  cubeSizeSelector.onchange = function(e) {    var cubeSize = e.target.value.split('x');    renderCubeWithTransistion(5, parseInt(cubeSize[0], 0), parseInt(cubeSize[1], 0), 80, 70, 0.3);  }
canvas {    border: 1px solid #000;  }  select {    display: block;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script>  <select id="cubeSizeSelector">    <option>5x5</option>    <option>5x10</option>    <option>10x5</option>  </select>    <canvas></canvas>

Answers 2

Drawing an extruded outline. Axonometric

Ideally you would create a generic axonometric renderer that given a floor plan renders the object to the canvas as needed.

You can then link the plan to a selection box and update the view when the selection has changed.

Best as a code example

The example below uses the object renderIsoPlan to render the shape.

Shapes are set via a plan. eg a box has a floor plan [[-1,-1],[1,-1],[1,1],[-1,1]] representing the 4 bottom corners.

The renderIsoPlan has the following properties

  • canvas The canvas that the shape is rendered to. Will not draw until this is set. renderIsoPlan will create a 2D context which will be the same if you have one already
  • height How far up the outline is projected.
  • style Canvas context style object eg {stokeStyle : "red", lineWidth : 2} draws 2 pixel with red lines.
  • plan Set of points for the floor. Points are moved to center automatically. eg [[0,-1],[1,1],[-1,1]] draws a triangle
  • scale Scale say no more
  • rotate Amount to rotate. If not 0 then projection is dimetric else it is trimetric.
  • centerY in unit size of canvas. ie 0.5 is center
  • centerX same as centerY

Call renderIsoPlan.refresh to draw

Note that you can not rotate the projection in the question as it visually appears to warp (change shape) thus if rotate is not 0 then a different projection is used.

Note the object is automatically centered around 0,0 use centerX, centerY to center in the view

setTimeout(start,0); // wait till Javascript parsed and executed  requestAnimationFrame(animate); // Animate checked at start so start anim    // named list of shapes  const boxes = {    box1By1 : {      plan : [[-1,-1],[1,-1],[1,1],[-1,1]],      scale : 35,      centerY : 0.75,    },    box1By2 : {      plan :  [[-1,-2],[1,-2],[1,2],[-1,2]],      scale : 30,      centerY : 0.7,    },    box2By2 : {      plan :  [[-2,-2],[2,-2],[2,2],[-2,2]],      scale : 25,      centerY : 0.7,    },    box2By1 : {      plan :  [[-2,-1],[2,-1],[2,1],[-2,1]],      scale : 30,      centerY : 0.7,    },    box1By3 : {      plan : [[-1,-3],[1,-3],[1,3],[-1,3]],      scale : 22,      centerY : 0.67,    },    box1By4 :{      plan :  [[-1,-4],[1,-4],[1,4],[-1,4]],      scale : 20,      centerY : 0.63,    },    lShape : {      plan : [[-2,-4],[0,-4],[0,2],[2,2],[2,4],[-2,4]],      scale : 20,      centerY : 0.65,   },    current : null,  }  // Sets the renderIsoPlan object to the current selection  function setShape(){    boxes.current = boxes[boxShape.value];    Object.assign(renderIsoPlan, boxes.current);    if (!animateCheckBox.checked) { renderIsoPlan.refresh() }  }  // When ready this is called  function start(){    renderIsoPlan.canvas = canvas;    renderIsoPlan.height = 2;    setShape();    renderIsoPlan.refresh();  }    // Add event listeners for checkbox and box selection   boxShape.addEventListener("change", setShape );  animateCheckBox.addEventListener("change",()=>{    if (animateCheckBox.checked) {      requestAnimationFrame(animate);    } else {      renderIsoPlan.rotate = 0;      setShape();    }  });      // Renders animated object  function animate(time){         if (animateCheckBox.checked) {      renderIsoPlan.rotate = time / 1000;      renderIsoPlan.refresh();      requestAnimationFrame(animate);    }  }      // Encasulate Axonometric render.  const renderIsoPlan = (() => {      var ctx,canvas,plan,cx,cy,w,h,scale,height, rotate;      height = 50;      scale = 10;      rotate = 0;      const style = {        strokeStyle : "#000",        lineWidth : 1,        lineJoin : "round",        lineCap : "round",      };      const depthScale = (2/3);        // Transforms then projects the point to 2D      function transProjPoint(p) {        const project = rotate !== 0 ? 0 : depthScale;        const xdx = Math.cos(rotate);        const xdy = Math.sin(rotate);        const y = p[0] * xdy + p[1] * xdx;        const x = p[0] * xdx - p[1] * xdy - y * project;        return [x,y * depthScale];      }            // draws the plan              function draw() {        ctx.setTransform(1, 0, 0, 1, 0, 0);        ctx.clearRect(0,0,w,h);              ctx.setTransform(scale, 0, 0, scale, cx, cy);        var i = plan.length;        ctx.beginPath();        while(i--){ ctx.lineTo(...transProjPoint(plan[i])) }        ctx.closePath();        i = plan.length;        ctx.translate(0,-height);        ctx.moveTo(...transProjPoint(plan[--i]))        while(i--){ ctx.lineTo(...transProjPoint(plan[i])) }        ctx.closePath();        i = plan.length;        while(i--){          const [x,y] = transProjPoint(plan[i]);          ctx.moveTo(x,y);          ctx.lineTo(x,y + height);        }        ctx.setTransform(1, 0, 0, 1, 0, 0);        ctx.stroke();        }      // centers the plan view on coordinate 0,0      function centerPlan(plan){        var x = 0, y = 0;        for(const point of plan){           x += point[0];           y += point[1];        }        x /= plan.length;        y /= plan.length;        for(const point of plan){           point[0] -= x;           point[1] -= y;        }        return plan;      }                      // Sets the style of the rendering      function setStyle(){        for(const key of Object.keys(style)){          if(ctx[key] !== undefined){            ctx[key] = style[key];          }        }      }        // define the interface    const API = {      // setters allow the use of Object.apply       set canvas(c) {        canvas = c;        ctx = canvas.getContext("2d");        w = canvas.width;  // set width and height        h = canvas.height;        cx = w / 2 | 0;    // get center        cy = h / 2 | 0; // move center down because plan is extruded up      },      set height(hh) { height = hh },      set style(s) { Object.assign(style,s) },      set plan(points) { plan = centerPlan([...points])  },      set scale(s) { scale = s },      set rotate(r) { rotate = r },      set centerY(c) { cy = c * h },      set centerX(c) { cx = c * w },            // getters not used in the demo      get height() { return height },      get style() { return style },      get plan() { return plan },      get scale() { return scale },      get rotate() { return r },      get centerY() { return cy / h },      get centerX() { return cx / w },            // Call this to refresh the view      refresh(){        if(ctx && plan){          ctx.save();          if(style){ setStyle() }          draw();          ctx.restore();        }      }    }    // return the interface    return API;  })();
canvas { border : 2px solid black; }
<select id="boxShape">   <option value = "box1By1">1 by 1</option>   <option value = "box1By2">1 by 2</option>   <option value = "box2By2">2 by 2</option>   <option value = "box2By1">2 by 1</option>   <option value = "box1By3">1 by 3</option>   <option value = "box1By4">1 by 4</option>   <option value = "lShape">L shape</option>  </select>  <input type="checkBox" id="animateCheckBox" checked=true>Animate</input><br>  <canvas id="canvas"></canvas>

Read More

Wednesday, January 17, 2018

Kivy: what is the proper method for animating images with canvas?

Leave a Comment

I am not fully understanding how to use canvas correctly for images with animations.

See the attached snippet, where I load an animated icon into an Image and do both: (1) add_widget the Image (2) create a Rectangle canvas instruction with a texture = Image's texture

The Image animates The Rectangle texture does not

I have read through all of the Kivy manual and read through Image and Canvas and I get the idea that Image is a nice high level class with all of this image animation handling and Canvas is more of a raw low-level drawing canvas.

So here is my question - what is the Kivy-correct architecture for handling animations on a Canvas? I looked at Animation but that seems for more matrix-like animations such as translation, scaling, rotation.

Here is what I am doing now: I have game with large map window and then a bunch of game UX in helper windows The game UX helper windows I do all the kivy layouts and such and use generally Images and so my icons are animating nicely

However in the game map, I am using canvas:

Drawing all of my game objects using this paradigm:

r=Rectangle(texture=some_Image.texture) map.canvas.add(r) 

When the world needs to be re-drawn:

1) map.canvas.clear()

2) draw all of the stuff in their new positions and states (to be faster, I should just track the dirty objects and locations and just draw those, but to be honest I am getting fantastic fps even with this nuclear-level clear on each draw)

This is of course a lot faster and lighter weight than creating and destroying hundreds of widget-classes - what map canvas is for - right?

But the problem is that my icons with animations in a zip file are not animating

Q: Am I thinking of canvas wrong? Should I instead be adding an Image for each of my game objects instead? (And take advantage of all the animated image support?)

from kivy.uix.relativelayout import RelativeLayout from kivy.uix.image import Image from kivy.app import App from kivy.graphics import Rectangle   class MainApp(App):     def __init__(self, **kwargs):         super().__init__(**kwargs)         self.root = RelativeLayout()          # use any zip file of an animated image         self.animated_icon = Image(source='factory_icon.zip')          # If I add an Image, the icon animates         self.root.add_widget(self.animated_icon)          # If I add the Image's texture on to a Rectangle instruction, no animation         r = Rectangle(texture=self.animated_icon.texture, size=(100, 100), pos=(100, 100))         self.root.canvas.add(r)      def build(self):         return self.root   if __name__ == '__main__':     MainApp().run() 

1 Answers

Answers 1

Image.texture property changes in time. It schedules internally methods to update it as the animation goes. This change doesn't propagate to your rectangle because you created it with texture value captured at a very certain point in time, between updates. Consider this example (I use a .gif file for the animation, but the principle should be the same):

from kivy.uix.relativelayout import RelativeLayout from kivy.uix.image import Image from kivy.app import App from kivy.graphics import Rectangle   class MainApp(App):     def __init__(self, **kwargs):         super(MainApp, self).__init__(**kwargs)         self.root = RelativeLayout()          animated_icon = Image(source='test.gif')         animated_icon.bind(texture=self.update_texture)          self.r = Rectangle(texture=animated_icon.texture, size=(500, 255), pos=(100, 100))         self.root.canvas.add(self.r)      def update_texture(self, instance, value):         self.r.texture = value      def build(self):         return self.root   if __name__ == '__main__':     MainApp().run() 

Here I bind my own update_texture method to image's texture property so every time it changes I can update the rectangle accordingly.

Read More

Saturday, November 11, 2017

How to play sound effect of spin wheel co-originated with the speed or Arc line

Leave a Comment

I want to play sound on rotating the wheel According to angle and coordinate the speed of wheel rotating

I want to Sound Play on right time when the Pin touch on - line touch of Arc.

Also, Want to Animation on Pin when touch like Shaking.

Sound is Play but the Sound Continuously play and seeking not Coordinates According to Canvas wheel

 @Override protected void onDraw(Canvas canvas) {     super.onDraw(canvas);     drawWheelBackground(canvas);     initComponents();      float tempAngle = 0;     float sweepAngle = 360 / mWheelItems.size();     if (this.mWheelItems != null) {          Log.e("mWheelItems.size()", String.valueOf(mWheelItems.size()));         for (int i = 0; i < mWheelItems.size(); i++) {             archPaint.setColor(mWheelItems.get(i).color);             archPaint1.setColor(Color.WHITE);              canvas.drawArc(range, tempAngle, sweepAngle, true, archPaint2);             canvas.drawArc(range, tempAngle, sweepAngle, true, archPaint);              drawImage(canvas, tempAngle, mWheelItems.get(i).bitmap, mWheelItems.get(i).mvalue, sweepAngle);          }         if (!(this.resourcePlayer == null)) {              if (this.resourcePlayer.isPlaying()) {                 resourcePlayer.setVolume(100, 100);                 this.resourcePlayer.seekTo(0);              } else {                  this.resourcePlayer.start();              }         }      } } 

Rotation according to wheelItemCenter and 360 degrees

   final float wheelItemCenter = 180 - getAngleOfIndexTarget(target) + (360 / mWheelItems.size()) / 2;     animate().setInterpolator(new DecelerateInterpolator())             .setDuration(DEFAULT_ROTATION_TIME)             .rotation((360*5) + wheelItemCenter) 

enter image description here

1 Answers

Answers 1

So if I'm understanding correctly, you want to adjust the sound based on the wheel's speed and play it whenever it hits one of your pins.

Playing it whenever it hits one of the pins should be a math-question, if it plays continuously that would mean that your wheel is spinning fast and that the sound you're playing is longer than the duration between hitting two pins, I assume.

You can play around with the speed and pitch of your sound. If you're using a MediaPlayer you can change the PlaybackParams according to this - check out setPitch and setSpeed.

The faster your wheel is, the higher is the speed / pitch of your sound. The slower it gets, the more you also slow down the sound.

Read More

Sunday, October 15, 2017

Forced Directed graph multiple edges using d3 canvas

Leave a Comment

I have created forced directed graph which has multiple edges , but after rending it shows only , other one overlaps on one another . I want to create something like https://bl.ocks.org/mattkohl/146d301c0fc20d89d85880df537de7b0#index.html

My Code : JSBIN

<!DOCTYPE html> <html> <head>         <title>Sample Graph Rendring Using Canvas</title>         <script src="https://rawgit.com/gka/randomgraph.js/master/randomgraph.js"></script>         <script src="https://d3js.org/d3.v4.min.js"></script> </head> <body>     <script>         var graph = {}//randomgraph.WattsStrogatz.beta(15, 4, 0.06);      graph.nodes = [{"label":"x"} , {"label":"y"}];     graph.edges = [{source:0,target:1},{source:0,target:1},                    {source:1,target:0}]          var canvas = null         var width = window.innerWidth,             height = window.innerHeight;         canvas = d3.select("body").append("canvas").attr("width",width).attr("height",height);          var context = canvas.node().getContext("2d");           force = d3.forceSimulation()                 .force("link", d3.forceLink().id(function(d) {                       return d.index;                 })).force("charge", d3.forceManyBody())                 .force("center", d3.forceCenter(width / 2, height / 2));          force.nodes(graph.nodes);         force.force("link").links(graph.edges).distance(200);          var detachedContainer = document.createElement("custom");             dataContainer = d3.select(detachedContainer);          link = dataContainer.selectAll(".link").data(graph.edges)               .enter().append("line").attr("class", "link")               .style("stroke-width", 2)          node = dataContainer.selectAll(".node").data(graph.nodes)               .enter().append("g");            var circles = node.append("circle")               .classed("circle-class", true)               .attr("class", function (d){ return "node node_" + d.index;})               .attr("r", 5)               .attr("fill", 'red')               .attr("strokeStyle", 'black');          d3.timer(function(){             context.clearRect(0, 0, width, height);              // draw links             link.each(function(d) {               context.strokeStyle = "#ccc";               /***** Elliptical arcs *****/               context.stroke(new Path2D(linkArc(d)));               /***** Elliptical arcs *****/             });              context.lineWidth = 2;             node.each(function(d) {                context.beginPath();               context.moveTo(d.x, d.y);               var r = d3.select(this).select("circle").node().getAttribute('r');                   d.x = Math.max(30, Math.min(width - 30, d.x));               d.y = Math.max(30, Math.min(height - 30, d.y));                        context.closePath();               context.arc(d.x, d.y, r, 0, 2 * Math.PI);                context.fillStyle = d3.select(this).select("circle").node().getAttribute('fill');               context.strokeStyle = d3.select(this).select("circle").node().getAttribute('strokeStyle');               context.stroke();               context.fill();                context.beginPath();               context.arc(d.x + 15, d.y-20, 5, 0, 2 * Math.PI);               context.fillStyle = "orange";               context.strokeStyle = "orange";               var data = d3.select(this).data();               context.stroke();               context.fill();               context.font = "10px Arial";               context.fillStyle = "black";               context.strokeStyle = "black";               context.fillText(parseInt(data[0].index),d.x + 10, d.y-15);             });          });          circles.transition().duration(5000).attr('r', 20).attr('fill', 'orange');          canvas.node().addEventListener('click',function( event ){            console.log(event)             // Its COMING ANY TIME INSIDE ON CLICK OF CANVAS         });          /***** Elliptical arcs *****/         function linkArc(d) {           var dx = d.target.x - d.source.x,               dy = d.target.y - d.source.y,               dr = Math.sqrt(dx * dx + dy * dy);           return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;         }         /***** Elliptical arcs *****/     </script> </body> </html>   

1 Answers

Answers 1

You can make the curve like this:

  //make a curve object    var curves = {};    function getCurveFactor(d){     var factor = 0.3;//you may change this as per your choice.     //make a key     var key = d.source.index + "---"+ d.target.index;     //see if the key is present in the object     if (curves[key]){       //if key is present you need a bigger curve      //so that it does not overlap       curves[key] = curves[key] + factor;     } else {       //no key present keep the curve simple       curves[key] = 1;     }     return curves[key];   } 

This function makes the arc:

    function arcPath(d) {                 var x1 = d.target.x,                     y1 = d.target.y,                     x2 = d.source.x,                     y2 = d.source.y,                     dx = x2 - x1,                     dy = y2 - y1,                     dr = Math.sqrt(dx * dx + dy * dy),                     drx = dr,                     dry = dr;                  //store the curve factor inside the data.                 if(!d.curve){                   d.curve = getCurveFactor(d);                 }                     return "M" + x1 + "," + y1 + "A" + (drx/d.curve) + ", " + (dry) + " " + 0 + ", " + 0 + ", " + 0 + " " + x2 + "," + y2;             } 

working code here

Read More

Monday, August 28, 2017

Canvas getImageData returning incorrect data on certain mobile devices

Leave a Comment

I am working on a canvas video player with some special features based on frames of the video. To overcome the unreliable timing in the video HTML5 tag the videos we are using have a barcode embedded in each frame indicating the current frame number. Using the canvas getImageData method I can grab the pixels and read the barcode to get the frame number. This works great and I have a JSFiddle demonstrating that it works (I couldn't get around CORS in this fiddle to serve the video to the canvas so to see it working you'll have to download the example video locally then upload it via the button. Not ideal but it works).

On certain mobile devices (only Android thus far) this logic breaks. The getImageData returns incorrect values.

It works correctly on my Samsung Galaxy S5 v6.0.1 but fails on a Google Pixel running android v7.1.2. I'll try to collect more data on which devices/OS versions it fails on.

For example, when playing on desktop the first iteration of getImageData returns:

Uint8ClampedArray(64) [3, 2, 3, 255, 255, 255, 255, 255, 246, 245, 247, 255, 243, 242, 243, 255, 241, 239, 241, 255, 242, 240, 242, 255, 242, 240, 242, 255, 242, 240, 242, 255, 242, 240, 242, 255, 242, 240, 242, 255, 242, 240, 242, 255, 242, 240, 242, 255, 242, 240, 242, 255, 242, 240, 242, 255, 242, 240, 242, 255, 242, 240, 242, 255] 

which correctly gets computed as framenumber 1.

However on the galaxy, the first iteration returns:

Uint8ClampedArray(64) [255, 242, 217, 255, 255, 234, 209, 255, 41, 1, 1, 255, 254, 235, 210, 255, 255, 234, 209, 255, 50, 4, 0, 255, 254, 240, 215, 255, 255, 248, 224, 255, 255, 249, 225, 255, 255, 251, 232, 255, 255, 252, 233, 255, 255, 252, 233, 255, 255, 253, 234, 255, 255, 255, 237, 255, 255, 255, 237, 255, 28, 1, 1, 255]  

I read that certain devices may being doing additional smoothing so I've been playing around with disabling it in the context via:

this.ctx.mozImageSmoothingEnabled = false; this.ctx.webkitImageSmoothingEnabled = false; this.ctx.msImageSmoothingEnabled = false; this.ctx.imageSmoothingEnabled = false;  

But it didn't help.

Here is the code being used in the JSFiddle.

var frameNumberDiv = document.getElementById('frameNumber'); function load() {     var canvas = document.getElementById('canvas');     var ctx = canvas.getContext('2d');     var video = document.getElementById('video');     canvas.width = 568;     canvas.height = 640;     video.addEventListener('play', function() {         var that = this; //cache         (function loop() {             if (!that.paused && !that.ended) {                 ctx.drawImage(that, 0, 0);                 var pixels = ctx.getImageData(0, 320 - 1, 16, 1).data;                 getFrameNumber(pixels);                 setTimeout(loop, 1000 / 30); // drawing at 30fps             }         })();     }, 0); }  function getFrameNumber(pixels) {      let j = 0;     let thisFrameNumber = 0;     let str = "Pixels: ";     for (let i = 0; i < 16; i++) {         str += pixels[j] + " ";         thisFrameNumber += getBinary(pixels[j], i);         j += 4;     }     document.getElementById('frameNumber').innerHTML = "FrameNumber: " + thisFrameNumber; }  function getBinary(pixel, binaryPlace) {     const binary = [1, 2, 4, 8, 16, 32, 64, 128, 256,         512, 1024, 2048, 4096, 8192, 16384, 32768     ];     if (pixel > 128) return 0;     if (pixel < 128 && binary[binaryPlace]) {         return binary[binaryPlace]     } else {         return 0;     } }  (function localFileVideoPlayer() {     'use strict';     var URL = window.URL || window.webkitURL;     var displayMessage = function(message, isError) {         var element = document.querySelector('#message');         element.innerHTML = message;         element.className = isError ? 'error' : 'info';     }     var playSelectedFile = function(event) {             console.log("Playing");         var file = this.files[0];         var type = file.type;         var videoNode = document.querySelector('video');         var canPlay = videoNode.canPlayType(type);         if (canPlay === '') canPlay = 'no';         var message = 'Can play type "' + type + '": ' + canPlay;         var isError = canPlay === 'no';         displayMessage(message, isError);          if (isError) {             return;         }          var fileURL = URL.createObjectURL(file);         videoNode.src = fileURL;         load();     }     var inputNode = document.querySelector('input')     inputNode.addEventListener('change', playSelectedFile, false) })(); 

EDIT

  • Works on a Nexus 6P running Android v6.0
  • Works on a Samsung 6 (Samsung SM G920A) running Android v 5.0.2
  • It DOES NOT work on a Samsung Galaxy S7 (SAMSUNG-SM-G935A) running Android v7.0

Could this possibly be an Android 7 issue?

Edit 2

In response to a question in the comments:

videoNode.videoHeight and videoWidth are both 0 on the google pixel for their entire existence but this is the same as on desktop. In both of the devices that don't work that I've encountered the image of each frame is fully painted. I'll attach a screen shot from the google pixel. When paused it consistently reads the same number. In other words it is not jumping around so whatever it is reading is truly on the frame of the video. enter image description here

EDIT 3: Discovery

I believe that I've made a relevant discovery/realization which I should have seen earlier.

When looking at the output of getImageData on the broken device I was stepping through line by line. What I hadn't (and should have) noticed was that the video element was continuing slightly after it hit my break points / debugger statements. By the time the getImageData method was executed the video had moved past the next frame. So, the scanned barcode was actually for a much later frame than expected.

I added some console log statements and let it run naturally. Looking at the output I can see a much more recognizable pattern.

Here is the first few readings on the google pixel:

Uint8ClampedArray(64) [255, 255, 255, 255, 246, 246, 246, 255, 243, 243, 243, 255, 240, 240, 241, 255, 241, 241, 242, 255, 241, 241, 242, 255, 241, 241, 242, 255, 241, 241, 242, 255, 241, 241, 242, 255, 241, 241, 242, 255, 241, 241, 242, 255, 241, 241, 242, 255, 241, 241, 242, 255, 241, 241, 242, 255, 241, 241, 242, 255, 2, 2, 2, 255]  Uint8ClampedArray(64) [5, 5, 5, 255, 255, 255, 255, 255, 251, 251, 251, 255, 247, 247, 248, 255, 245, 245, 245, 255, 245, 245, 245, 255, 246, 246, 246, 255, 246, 246, 246, 255, 246, 246, 246, 255, 246, 246, 246, 255, 246, 246, 246, 255, 246, 246, 246, 255, 246, 246, 246, 255, 246, 246, 246, 255, 246, 246, 246, 255, 6, 3, 2, 255]  Uint8ClampedArray(64) [235, 231, 230, 255, 17, 12, 12, 255, 252, 247, 247, 255, 255, 255, 255, 255, 255, 254, 254, 255, 255, 253, 253, 255, 255, 252, 251, 255, 255, 253, 253, 255, 255, 253, 253, 255, 255, 253, 253, 255, 255, 253, 253, 255, 255, 253, 253, 255, 255, 253, 253, 255, 255, 253, 253, 255, 255, 253, 253, 255, 7, 3, 1, 255]  Uint8ClampedArray(64) [26, 15, 14, 255, 4, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10, 0, 0, 255] 

As you may notice, the results seem to be correct however they are shifted one pixel to the left.

I modified the JSFiddle slightly to shift the getImageData read over by a pixel and it gives the exact same response as on the Pixel.

var pixels = ctx.getImageData(1, 320 - 1, 16, 1).data; 

Doing -1 seems to have no effect.

So, for some reason these devices are either shifting the entire texture over by a pixel or there is something wrong with the getImageData Method.

EDIT 4

As an experiment I reconfigured my code to use a webGL texture. Same behaviour on desktop/mobile devices. This allowed me to use -1 as the x target using gl.readPixels. I was hoping that by skipping using canvas the entire image would be stored in memory and I could access the pixel data I needed.... Didn't work but here is the data it produced which shows that it is also shifted using purely webGL.

Uint8Array(64) [0, 0, 0, 0, 255, 248, 248, 255, 25, 18, 18, 255, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]  Uint8Array(64) [0, 0, 0, 0, 255, 254, 247, 255, 255, 244, 236, 255, 48, 18, 10, 255, 254, 246, 238, 255, 255, 247, 239, 255, 255, 247, 239, 255, 255, 248, 241, 255, 255, 251, 243, 255, 255, 251, 243, 255, 255, 251, 243, 255, 255, 251, 243, 255, 255, 251, 243, 255, 255, 251, 243, 255, 255, 250, 240, 255, 255, 250, 240, 255]  Uint8Array(64) [0, 0, 0, 0, 31, 0, 0, 255, 254, 243, 230, 255, 43, 6, 1, 255, 254, 243, 230, 255, 255, 244, 231, 255, 255, 244, 231, 255, 255, 244, 231, 255, 255, 244, 231, 255, 255, 244, 231, 255, 255, 244, 231, 255, 255, 244, 231, 255, 255, 244, 231, 255, 255, 244, 231, 255, 255, 244, 229, 255, 255, 244, 229, 255] 

Using:

gl.readPixels(-1, height, 16, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels); 

Edit 5

Ok, I promised I would get more details on which devices were failing/not. I had some online QA testing done using a slightly modified JSFiddle. I modified it slightly to help make it a bit more idiot proof for the general public to work with.

The responses were unfortunately fairly mixed. I was hoping it would be isolated to Android 7 but that doesn't seem to be the case.

I have a CSV on my google drive with the results of this test. Not that these tests are 100% reliable but it seems like it's just some random devices......

0 Answers

Read More

Thursday, August 10, 2017

Canvas .toDataURL() returns partially corrupted image

Leave a Comment

We have a web application that (very intermittently) is returning a partially corrupted PNG image data URL. The image has a large black section covering some of the image but not all of it. These images are customer signatures.
For example:

enter image description here

We are using the signature pad component from this. The image URL is returned using the getSignatureImage() routine.

The only thing I have seen from the access logs seems to show the affected requests coming from "Samsung Galaxy Tab" devices, but using Chrome 59. However other requests from the same devices work OK.

Any help appreciated.

1 Answers

Answers 1

I think it is not a memory issue. When image consumes too much memory, an image will by simply black (empty pixels rgb(0,0,0)). Try to get blob from canvas - canvas.toBlob(function(blob) {}). Probably your image not loaded or draw yet. Try to put window.setTimeout somewhere before you get the image data (base64 or blob)

Read More

Monday, April 3, 2017

Fragment vs Activity canvas drawing on android

Leave a Comment

I designed a surfaceview, where it's canvas is drawn using a thread (Game loop). The Game loop draws 300 small images.

If I load this surfaceview on activity, the time to execute a frame is 5- 10 ms lower than if I load it on a fragment (withing an activity).

Test results 300 images loop- activity (24 millsec) , Fragment (32 millsec).

What is the reason behind this? How can I improve the performance in Fragment?

Here is my code. The loop at the end is the bottleneck. clusters list could have 300 items to draw.

public List<PCluster> clusters = new ArrayList<PCluster>();      public void doDraw(Canvas canvas) {      try {         if (canvas == null) {             return;         }         super.draw(canvas);          canvas.drawColor(backColor);         if (waitTillLoad) {             return;         }      } catch (Exception ex) {     }     final int savedState = canvas.save();     try {          minX = (int) (((viewWidth / mScaleFactor) - Gen.screenSizeWidth) / 2) * Utils.VIEW_SIZE;         minY = (int) (((viewHeight / mScaleFactor) - Gen.screenSizeHeight) / 2) * Utils.VIEW_SIZE;          if (mPosX > maxX) {             mPosX = maxX;         }         if (mPosX < minX) {             mPosX = minX;         }         if (mPosY > maxY) {             mPosY = maxY;         }         if (mPosY < minY) {             mPosY = minY;         }           canvas.scale(mScaleFactor, mScaleFactor);         canvas.translate(mPosX, mPosY);          long startTime = System.currentTimeMillis();         if (!showBackground) {              for (PCluster cluster : clusters) {                 if (cluster.isVisible) {                     canvas.drawBitmap(cluster.Picture, cluster.BoardLocation.left,                             cluster.BoardLocation.top, null);                 }             }             Log.d("myApp", "   " + (System.currentTimeMillis() - startTime));         }      } catch (Exception ex) {     } finally {         canvas.restoreToCount(savedState);     } } 

This is main activity layout. @+id/fragment is used to load the layout below which has SurfaceView LinearLayout where the surface view is inserted at run time and where the drawing happens.

Main Layout

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >  <LinearLayout     android:id="@+id/fragment_fake"     android:layout_width="0dp"     android:layout_height="0dp"     android:gravity="center"     android:orientation="vertical"     android:layout_above="@+id/fragment"/>  <LinearLayout     android:id="@+id/fragment"     android:layout_width="fill_parent"     android:layout_height="fill_parent"      android:gravity="center"      android:orientation="vertical"     android:layout_above="@+id/fragment_ad"/>   <fragment     android:id="@+id/fragment_ad"     android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:layout_alignParentBottom="true"     class="controllers.AdFragment" />  </RelativeLayout> 

Game Layout with surface view

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal">   <LinearLayout     android:id="@+id/surfaceView"     android:orientation="vertical"     android:layout_width="match_parent"     android:layout_height="match_parent"/>  <include     android:id="@+id/gamesettingpanel"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:layout_alignParentTop="true"     layout="@layout/gameoption_panel" />  <include     android:id="@+id/scorepanel"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:layout_gravity="top"     android:layout_alignParentTop="true"     android:layout_centerHorizontal="true"     android:gravity="center_horizontal"     layout="@layout/scorepanel" />  <include     android:id="@+id/chaetpanel"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:layout_gravity="bottom"     layout="@layout/gamecheat_panel" />  <include     android:id="@+id/finishpanel"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:layout_centerHorizontal="true"     android:gravity="center_horizontal"     android:layout_alignParentTop="true"     layout="@layout/finishedpanel" /> 

0 Answers

Read More

Wednesday, March 15, 2017

2 animated elements stacked on top of each other changing (z-index position) when animating on IOS Devices?

Leave a Comment

JS FIDDLE

I have 2 animated elements. One is a simple rotation script which rotates the middle portion of the logo like a coin. 

The other animation is the particles canvas smoke animation behind the logo that you see while the middle section is flipping.

The problem i have is the canvas smoke animation changes its position and the coin flipping animation goes behind and in front of the smoke canvas animation hiding itself or part of itself like almost its z-index position changes when the flipping animation starts...

This only happens on Iphone and apple devices. but works fine on android and desktop.  If you remove the canvas the flipping animation works great with no issue.. But if the canvas is there it covers up the flip animation once the flip animation begins. 

I cant use my animation until i figure this out though.. Which is making me sad. lol

Any help is much appreciated! Check out my full JS FIDDLE

enter image description here

1 Answers

Answers 1

You can try moving the canvas element back in 3D space on its z-axis to avoid the clipping that occurs. For example, add these properties to the CSS rules:

.animateVSS{   /* ... */   -webkit-transform-style: preserve-3d;   transform-style: preserve-3d; }  #myCanvas{   /* ... */   -webkit-transform: translateZ(-20000px) rotateY(0.1deg);   transform: translateZ(-20000px) rotateY(0.1deg); } 

The numbers -20000 for translateZ is arbitrary in the example above. Play around with them until you find a more useful value, but this is a OK starting point. It's linked to the perspective setting which if set would also have an effect on what value is used for the z-position.

You can probably do fine with use the -webkit- prefixed variants as it only affects Safari, but for future it may be need for the unprefixed as well.

You can also remove the z-index for myCanvas as there is anyways a typo in it, and if corrected if will come on top.

Example fiddle

Read More

Monday, March 13, 2017

Use Chrome DevTools for rendering measurement for HTML5 graphics

Leave a Comment

I would like to measure the performance between canvas and svg in HTML5.

I have done so far. I have created multiple circles in svg and canvas. Both have a 500 x 500 Element width and height.

I found out I am measuring the scripting time. If I use the dev tools in Chrome, the scripting time is nearly equal to my measured time. Now, how can I measure the rendering time? Would be a code with separate canvas and svg circle creation and devtools for rendering a good way to compare svg and canvas rendering performance?

<html>     <head>         <script type="text/javascript">             var svgNS = "http://www.w3.org/2000/svg";             function createCircle1() {                 var t3 = performance.now();                 for (var x = 1; x <= 1000; x++) {                     for (var y = 1; y <= 100; y++) {                         var c = document.getElementById("myCanvas");                         var ctx = c.getContext("2d");                         ctx.beginPath();                         ctx.arc(x, y, 5, 0, 2 * Math.PI);                         ctx.stroke();                      }                 }                 var t4 = performance.now();                  console.log("canvas time " + (t4 - t3) + " milliseconds.")                  var t0 = performance.now();                 for (var x = 1; x <= 1000; x++) {                     for (var y = 1; y <= 100; y++) {                         var myCircle = document.createElementNS(svgNS, "circle"); //to create a circle, for rectangle use rectangle                         myCircle.setAttributeNS(null, "cx", x);                         myCircle.setAttributeNS(null, "cy", y);                         myCircle.setAttributeNS(null, "r", 5);                         myCircle.setAttributeNS(null, "stroke", "none");                         document.getElementById("mySVG").appendChild(myCircle);                     }                 }                 var t1 = performance.now();                  console.log("svg time " + (t1 - t0) + " milliseconds.")             }         </script>     </head>     <body onload="createCircle1();">         <svg id="mySVG" width="500" height="500" style="border:1px solid #d3d3d3;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"></svg>         <canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;"></canvas>     </body> </html> 

This is the result of my code enter image description here

Somehow the scripting time and my measured performance time is different. Can someone tell me if this performance comparison is useful?

I did the test multiple times, the performance time is always different but canvas is faster than svg in rendering and also in scripting.

Why in rendering? Scripting should be because of the DOM reference of svg?

This test I did with seperate svg and canvas, I just rendered first only svg, and in the next test only canvas.

1 Answers

Answers 1

The problem with SVG.

Below is a performance test of drawing a big circle on a canvas and a SVG image.

Both get about the same performance 30ms per circle on my machine and chrome.

Run the test and see the result. If you watch the progress you may notice that it begins to slow down a little. When the first test is run click the button again and this time you will notice that there is even more of a slow down.

Do a 3rd test and slower still, but the performance per circle for both canvas and SVG has not changed, where is the slow down coming from.

The DOM is not javascript.

The code run to add a node to the SVG does not care how many nodes the SVG has, but when add nodes to the SVG image and your code exits you have informed the DOM that your SVG element is dirty and needs to be redrawn.

I grouped the test into groups of ~10 before exiting. This means that for every ten circles added the DOM will redraw all the SVG nodes from scratch and outside the javascript context and your ability to measure or control it.

When you click test the second time the SVG already has 10000 circles, so after adding the first ten the DOM happily re-renders 10000+10 circles.

It is next to impossible to get an accurate measure of SVG performance.

Using timeline

I ran the code snippet below with timeline recording. I ran the test two times.

The next two images show the same period. The top one is at the start of the test and the next one is at the end of the second test.

I have mark the GPU sections that are likely involved in rendering the SVG. Note how they change from trivial to excessive.

enter image description here

enter image description here

This image shows one cycle of the test 10 renders in the second test cycle. The code execution is barely visible at ~1ms but the GPU is flat out with a huge 175ms devoted to drawing all the SVG circle again.

enter image description here

When you use SVG you must remember that when you make a change to it the DOM will re-render all of it. It does not care if it's visible or not. If you change the size it's redrawn.

To use SVG you must bundle all your calls into one execution context to get the best performance.

Canvas V SVG

Both SVG and Canvas use the GPU with very similar shaders to do the work. Drawing a circle in SVG or Canvas takes the same time. The advantage that the canvas has over SVG is that you control the rendering, what when and where. For SVG you only control content and have little say over rendering.

          var running = false;      var test = function(){          if(running){             return;          }          var mySVG = document.getElementById("mySVG");          var myCanvas = document.getElementById("myCanvas");          var ctx = myCanvas.getContext("2d");          var myCircle = document.createElementNS("http://www.w3.org/2000/svg", "circle");          running = true;          const testCount = 1000;          const groupCount = 10;          var times = [[],[]];               var names =["Canvas test.","SVG test."];          var indexs = [0,0];          var tests = [function(){                now = performance.now();              ctx.beginPath();              ctx.arc(250, 250, 250, 0, 2 * Math.PI);              ctx.fill();              return performance.now()-now;          },          function(){                now = performance.now();              var circle = myCircle.cloneNode();               circle.setAttributeNS(null, "cx", 250);              circle.setAttributeNS(null, "cy", 250);              circle.setAttributeNS(null, "r", 250);              circle.setAttributeNS(null, "stroke", "none");              mySVG.appendChild(circle);              return performance.now()-now;          }];          for(var i = 0; i < testCount; i ++){  // preallocate and zeor arrays              times[0][i] = 0;              times[1][i] = 0;          }          var testComplete = false;          function doTests(){              for(i = 0; i < groupCount; i ++){                  var testIndex = Math.floor(Math.random()*2);                  times[testIndex][indexs[testIndex]] = tests[testIndex]();                  indexs[testIndex] += 1;                  if(indexs[testIndex] >= testCount){                       testComplete = true;                       return;                  }                          }          }          function getResults(){              // get the mean              var meanA = 0;              var meanB = 0;              var varianceA = 0;              var varianceB = 0;              var totalA = 0;              var totalB = 0;              for(var i = 0; i < testCount; i ++){  // preallocate and zero arrays                  totalA += i < indexs[0] ? times[0][i] : 0;                  totalB += i < indexs[1] ? times[1][i] : 0;              }              meanA = Math.floor((totalA / indexs[0]) * 1000) / 1000;              meanB = Math.floor((totalB / indexs[1]) * 1000) / 1000;                for(var i = 0; i < testCount; i ++){  // preallocate and zero arrays                  varianceA += i < indexs[0] ? Math.pow((times[0][i] - meanA),2) : 0;                  varianceB += i < indexs[1] ? Math.pow((times[1][i] - meanB),2) : 0;              }              varianceA = Math.floor((varianceA / indexs[0]) * 1000) / 1000;              varianceB = Math.floor((varianceB / indexs[1]) * 1000) / 1000;              result1.textContent = `Test ${names[0]} Mean : ${meanA}ms Variance : ${varianceA}ms Total : ${totalA.toFixed(3)}ms over ${indexs[0]} tests.`;              result2.textContent = `Test ${names[1]}. Mean : ${meanB}ms Variance : ${varianceB}ms Total : ${totalB.toFixed(3)}ms over ${indexs[1]} tests.`;             }                      function test(){               doTests();               var p = Math.floor((((indexs[0] + indexs[1]) /2)/ testCount) * 100);               if(testComplete){                   getResults();                   p = 100;                   running = false;               }else{                   setTimeout(test,10);               }               progress.textContent = p+"%";            }                       test()      }        startBut.addEventListener("click",test);
    #ui {        font-family : Arial;      }
    <div id="ui">          <h3>Comparative performance test</h3>          Adding circles to canvas V adding circles to SVG.<br> The test adds 1000 * 10 circles to the canvas or SVG with as much optimisation as possible and to be fair.<br>          <input id="startBut" type="button" value = "Start test"/>          <div id="progress"></div>          <div id="result1"></div>          <div id="result2"></div>          <h3>SVG element</h3>          <svg id="mySVG" width="500" height="500" style="border:1px solid #d3d3d3;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"></svg>          <h3>Canvas element</h3>          <canvas id="myCanvas" width="500" height="500" style="border:1px solid #d3d3d3;"></canvas>       </div>

Read More

Saturday, July 23, 2016

Nice Drag and drop on a canvas HTML5

Leave a Comment

I try to implement a nice drag and drop on a canvas representing 3 disks.

I would like to change with mouse the position of each mass. My main problem is that I am constrained by the length of axe for each of these 3 spheres.

For the moment, I have implemented the following function when mouse is moving inside the canvas ( value of indexMass indicates which mass is moved : 1, 2 or 3 and t1, t2, t3 represents respectively the angle of mass 1, 2, 3 ) :

// Happens when the mouse is moving inside the canvas function myMove(event) {     if (isDrag) {      var x = event.offsetX;      var y = event.offsetY;       if (indexMass == 1)        { // Update theta1 value          t1 = t1 + 0.1*Math.atan(y/x);        }      else if (indexMass == 2)        { // Update theta2 value          t2 = t2 + 0.1*Math.atan(y/x);        }      else if (indexMass == 3)        { // Update theta3 value          t3 = t3 + 0.1*Math.atan(y/x);        }       // Update drawing      DrawPend(canvas);      }      } 

As you can see, I did for each angle :

t = t + 0.1*Math.atan(y/x); 

with :

 var x = event.offsetX;  var y = event.offsetY; 

But this effect is not very nice. Once the sphere is selected with mouse (on mouse click), I would like the cursor to be stucked with this sphere or the sphere to follow the "delta" of the mouse coordinates when I am not on sphere anymore.

To summarize, I don't know how to create a fine and user friendly drag and drop, if someone could help me or give me some advices, this would be great.

Thanks

UPDATE 1

@Blindman67 : thanks for your help, your code snippet is pretty complex for me, I didn't understand it all. But I am on the right way.

I am starting by the first issue : make rotate the selected disk with mouse staying very closed to it or over it, when dragging.

For the moment, I have modified my function myMove (which is called when I have clicked down and move the mouse for dragging) like :

// Happens when the mouse is moving inside the canvas function myMove(event) {     // If dragging     if (isDrag) {       // Compute dx and dy before calling DrawPend      var lastX = parseInt(event.offsetX - mx);      var lastY = parseInt(event.offsetY - my);       var dx = lastX - window['x'+indexMass];      var dy = lastY - window['y'+indexMass];       // Change angle when dragging      window['t'+indexMass] = Math.atan2(dy, dx);       // Update drawing      DrawPend(canvas);       // Highlight dragging disk      fillDisk(indexMass, 'pink');      }                      } 

where indexMass is the index of dragged disk and window['x'+indexMass] , window['y'+indexMass] are the current coordinates of the selected disk center.

After, I compute the dx, dy respectively from coordinates mouse clicked when starting drag (mx, my returned by getMousePos function) and mouse coordinates with moving.

Finally, I change the angle of disk by set, for global variable (theta of selected disk), i.e window['t'+indexMass] :

// Change angle when dragging window['t'+indexMass] = Math.atan2(dy, dx); 

I have took your part of code with Math.atan2.

But the result of this function doesn't make a good animation with mouse dragging, I would like to know where this could come from.

Right now, I would like to implement only the dragging without modifying the length of axis, I will see more later for this functionality.

UPDATE 2

I keep going on to find a solution about the dragging of a selected mass with mouse.

For trying a synthesis of what I have done previously, I believe the following method is good but this dragging method is not working very well : the selected disk doesn't follow correctly the mouse and I don't know why.

In myMove function (function called when I start dragging), I decided to :

  1. Compute the dx, dy between the mouse coordinates and the selected disk coordinates, i.e :

var dx = parseInt(event.offsetX - window['x'+indexMass]);

var dy = parseInt(event.offsetY - window['y'+indexMass]);

indexMass represents the index of the selected disk.

  1. Increment the position of selected disk (stored in temporary variables tmpX, tmpY) by dx, dy.

  2. Compute the new angle theta (identified in code by global variable window['t'+indexMass]

  3. Compute the new positions of selected disk with this new value of theta, i.e for example with disk1 (indexMass=1 and theta = t1) :

    x1= x0 +l1 * sin(t1) y1= y0 +l1 * sin(t1) 

I have to make you notice that I want dragging with mouse not to modify the lengths of axes with mouse, this is a constraint.

Here's the entire myMove function (called when drag is starting) :

// Happens when the mouse is moving inside the canvas function myMove(event) {     // If dragging     if (isDrag) {       console.log('offsetX', event.offsetX);      console.log('offsetY', event.offsetY);      var dx = parseInt(event.offsetX - window['x'+indexMass]);      var dy = parseInt(event.offsetY - window['y'+indexMass]);      console.log('dx', dx);      console.log('dy', dy);        // Temp variables       var tmpX = window['x'+indexMass];         var tmpY = window['y'+indexMass];          // Increment temp positions       tmpX += dx;       tmpY += dy;       // Compute new angle for indexMass       window['t'+indexMass] = Math.atan2(tmpX, tmpY);          console.log('printf', window['t'+indexMass]);        // Compute new positions of disks       dragComputePositions();        // Update drawing       DrawPend(canvas);        // Highlight dragging disk       fillDisk(indexMass, 'pink');     } } 

UPDATE 4 - Bounty :

Problem solved ! I forgot to take into account the position of "indexMass-1" disk to compute the new angle with Math.atan2 function.

1 Answers

Answers 1

You can not move the OS mouse position. You can hide the mouse canvas.style.cursor = "none"; and then draw a mouse on the canvas your self but it will lag behind by one frame because when you get the mouse coordinates the OS has already placed the mouse at that position, and if you use requestAnimationFrame (RAF) the next presentation of the canvas will be at the next display refresh interval. If you don't use RAF you may or may not present the canvas on the current display refresh, but you will get occasional flicker and shearing.

To solve the problem (which is subjective) draw a line from the rotation point through the ball to the mouse position this will at least give the user some feedback as to what is happening.

I would also add some handles to the balls so you could change the mass (volume of sphere * density) and the length of axis.. The resize cursors are a problem as the will not match the direction of required movement when the angles have changes. You would need to find one closest to the correct angle or render a cursor to a canvas and use that.

Example code shows what I mean. (does not include sim) Move mouse over balls to move, when over you will also see two circles appear to change distance and radius (mass)

/*-------------------------------------------------------------------------------------   answer code  ---------------------------------------------------------------------------------------*/              var balls = [];  var startX,startY;  var mouseOverBallIndex = -1;  var mouseOverDist = false;  var mouseOverMass = false;  const DRAG_CURSOR = "move";  const MASS_CURSOR = "ew-resize";  const DIST_CURSOR = "ns-resize";  var dragging = false;  var dragStartX = 0;  var dragStartY = 0;  function addBall(dist,radius){      balls.push({          dist : dist,          radius : Math.max(10,radius),          angle : -Math.PI / 2,          x : 0,          y : 0,          mass : (4/3) * radius * radius * radius * Math.PI,      });  }  function drawBalls(){      var i = 0;      var len = balls.length;      var x,y,dist,b,minDist,index,cursor;      ctx.lineWidth = 2;      ctx.strokeStyle = "black";      ctx.fillStyle = "blue"      ctx.beginPath();      x = startX;      y = startY;      ctx.moveTo(x, y)      for(; i < len; i += 1){          b = balls[i];          x += Math.cos(b.angle) * b.dist;          y += Math.sin(b.angle) * b.dist;          ctx.lineTo(x, y);          b.x = x;          b.y = y;      }      ctx.stroke();      minDist = Infinity;      index = -1;      for(i = 0; i < len; i += 1){          b = balls[i];          ctx.beginPath();          ctx.arc(b.x, b.y, b.radius, 0, Math.PI * 2);          ctx.fill();          if(!dragging){              x = b.x - mouse.x;              y = b.y - mouse.y;              dist = Math.sqrt(x * x + y * y);              if(dist < b.radius + 5 && dist < minDist){                  minDist = dist;                  index = i;              }          }      }      if(!dragging){          mouseOverBallIndex = index;          if(index !== -1){              cursor = DRAG_CURSOR;              b = balls[index];              ctx.fillStyle = "Red"              ctx.beginPath();              ctx.arc(b.x, b.y, b.radius, 0, Math.PI * 2);              ctx.fill();              dx = b.x - Math.cos(b.angle) * b.radius;              dy = b.y - Math.sin(b.angle) * b.radius;              x = dx - mouse.x;              y = dy - mouse.y;              dist = Math.sqrt(x * x + y * y);              ctx.beginPath();              if(dist < 6){                  ctx.strokeStyle = "Yellow"                  mouseOverDist = true;                  ctx.arc(dx, dy, 12, 0, Math.PI * 2);                  cursor = DIST_CURSOR;              }else{                  ctx.strokeStyle = "black"                  mouseOverDist = false;                  ctx.arc(dx, dy, 5, 0, Math.PI * 2);                }              ctx.stroke();MASS_CURSOR              dx = b.x - Math.cos(b.angle + Math.PI/2) * b.radius;              dy = b.y - Math.sin(b.angle + Math.PI/2) * b.radius;              x = dx - mouse.x;              y = dy - mouse.y;              dist = Math.sqrt(x * x + y * y);              ctx.beginPath();              if(dist < 6){                  ctx.strokeStyle = "Yellow"                  mouseOverMass = true;                  ctx.arc(dx, dy, 12, 0, Math.PI * 2);                  cursor = MASS_CURSOR;              }else{                  ctx.strokeStyle = "black"                  mouseOverMass = false;                  ctx.arc(dx, dy, 5, 0, Math.PI * 2);                }              ctx.stroke();              canvas.style.cursor = cursor;          }else{              canvas.style.cursor = "default";          }      }else{          b = balls[mouseOverBallIndex];          ctx.fillStyle = "Yellow"          ctx.beginPath();          ctx.arc(b.x, b.y, b.radius, 0, Math.PI * 2);          ctx.fill();                        }    }  function display(){  // put code in here      var x,y,b          if(balls.length === 0){          startX = canvas.width/2;          startY = canvas.height/2;          addBall((startY * 0.8) * (1/4), startY * 0.04);          addBall((startY * 0.8) * (1/3), startY * 0.04);          addBall((startY * 0.8) * (1/2), startY * 0.04);                }      ctx.setTransform(1,0,0,1,0,0); // reset transform      ctx.globalAlpha = 1;           // reset alpha      ctx.clearRect(0,0,w,h);      if((mouse.buttonRaw & 1) && mouseOverBallIndex > -1){          b = balls[mouseOverBallIndex];          if(dragging === false){              dragging = true;              dragStartX = balls[mouseOverBallIndex].x;              dragStartY = balls[mouseOverBallIndex].y;          }else{              b = balls[mouseOverBallIndex];              if(mouseOverBallIndex === 0){                  x = startX;                  y = startY;              }else{                  x = balls[mouseOverBallIndex-1].x                  y = balls[mouseOverBallIndex-1].y              }              if(mouseOverDist){                  var dist = Math.sqrt(Math.pow(x-mouse.x,2)+Math.pow(y-mouse.y,2));                  b.dist = dist + b.radius;                                }else                  if(mouseOverMass){                  var dist = Math.sqrt(Math.pow(dragStartX-mouse.x,2)+Math.pow(dragStartY-mouse.y,2));                  b.radius = Math.max(10,dist);                  b.mass = dist * dist * dist * (4/3) * Math.PI;              }else{                  b.angle = Math.atan2(mouse.y - y, mouse.x - x);                  ctx.beginPath();                  ctx.lineWidth = 1;                  ctx.strokeStyle = "grey";                  ctx.moveTo(x,y);                  ctx.lineTo(mouse.x, mouse.y);                  ctx.stroke();              }          }                }else if(dragging){          dragging = false;      }        drawBalls();  }    /*-------------------------------------------------------------------------------------   answer code END  ---------------------------------------------------------------------------------------*/                                                                            /** SimpleFullCanvasMouse.js begin **/  const CANVAS_ELEMENT_ID = "canv";  const U = undefined;  var w, h, cw, ch; // short cut vars   var canvas, ctx, mouse;  var globalTime = 0;   var createCanvas, resizeCanvas, setGlobals;  var L = typeof log === "function" ? log : function(d){ console.log(d); }  createCanvas = function () {      var c,cs;      cs = (c = document.createElement("canvas")).style;       c.id = CANVAS_ELEMENT_ID;          cs.position = "absolute";      cs.top = cs.left = "0px";      cs.zIndex = 1000;      document.body.appendChild(c);       return c;  }  resizeCanvas = function () {      if (canvas === U) { canvas = createCanvas(); }      canvas.width = window.innerWidth;      canvas.height = window.innerHeight;       ctx = canvas.getContext("2d");       if (typeof setGlobals === "function") { setGlobals(); }  }  setGlobals = function(){ cw = (w = canvas.width) / 2; ch = (h = canvas.height) / 2; balls.length = 0; }  mouse = (function(){      function preventDefault(e) { e.preventDefault(); }      var mouse = {          x : 0, y : 0, w : 0, alt : false, shift : false, ctrl : false, buttonRaw : 0,          over : false,  // mouse is over the element          bm : [1, 2, 4, 6, 5, 3], // masks for setting and clearing button raw bits;          mouseEvents : "mousemove,mousedown,mouseup,mouseout,mouseover,mousewheel,DOMMouseScroll".split(",")      };      var m = mouse;      function mouseMove(e) {          var t = e.type;          m.x = e.offsetX; m.y = e.offsetY;          if (m.x === U) { m.x = e.clientX; m.y = e.clientY; }          m.alt = e.altKey; m.shift = e.shiftKey; m.ctrl = e.ctrlKey;          if (t === "mousedown") { m.buttonRaw |= m.bm[e.which-1]; }            else if (t === "mouseup") { m.buttonRaw &= m.bm[e.which + 2]; }          else if (t === "mouseout") { m.buttonRaw = 0; m.over = false; }          else if (t === "mouseover") { m.over = true; }          else if (t === "mousewheel") { m.w = e.wheelDelta; }          else if (t === "DOMMouseScroll") { m.w = -e.detail; }          if (m.callbacks) { m.callbacks.forEach(c => c(e)); }          e.preventDefault();      }      m.addCallback = function (callback) {          if (typeof callback === "function") {              if (m.callbacks === U) { m.callbacks = [callback]; }              else { m.callbacks.push(callback); }          } else { throw new TypeError("mouse.addCallback argument must be a function"); }      }      m.start = function (element, blockContextMenu) {          if (m.element !== U) { m.removeMouse(); }                  m.element = element === U ? document : element;          m.blockContextMenu = blockContextMenu === U ? false : blockContextMenu;          m.mouseEvents.forEach( n => { m.element.addEventListener(n, mouseMove); } );          if (m.blockContextMenu === true) { m.element.addEventListener("contextmenu", preventDefault, false); }      }      m.remove = function () {          if (m.element !== U) {              m.mouseEvents.forEach(n => { m.element.removeEventListener(n, mouseMove); } );              if (m.contextMenuBlocked === true) { m.element.removeEventListener("contextmenu", preventDefault);}              m.element = m.callbacks = m.contextMenuBlocked = U;          }      }      return mouse;  })();  var done = function(){      window.removeEventListener("resize",resizeCanvas)      mouse.remove();      document.body.removeChild(canvas);          canvas = ctx = mouse = U;      L("All done!")  }    resizeCanvas(); // create and size canvas  mouse.start(canvas,true); // start mouse on canvas and block context menu  window.addEventListener("resize",resizeCanvas); // add resize event    function update(timer){ // Main update loop      globalTime = timer;      display();  // call demo code      // continue until mouse right down      if (!(mouse.buttonRaw & 2)) { requestAnimationFrame(update); } else { done(); }  }  requestAnimationFrame(update);    /** SimpleFullCanvasMouse.js end **/

Read More

Saturday, April 23, 2016

Smooth color transition between multiple color stops

Leave a Comment

I am trying to draw Scroll reach map of my website using canvas. I have bunch Y coordinates and the number of visitors who reached the point. I am coloring each coordinates using the number of visitors who reached the point. Let's say

10 users are visiting my website.

5 users scrolling upto = 0, 300px 3 users scrolling upto = 300, 700px 2 users scrolling upto = 700, 800px

Now, I have 3 color stops (300, 700, 800)px respectively. And the coloring should be based on the number of users. I did this but the transition between the stops are smooth, it looks solid.

var Scroll = function(config, data) {     var container, computed;     this.data = data;     this.config = config;     container = document.querySelector(this.config.container);     this.canvas = document.createElement('canvas');     this.ctx = this.canvas.getContext('2d');     computed = getComputedStyle(container) || {};     this.canvas.className = 'zarget-scrollmap-canvas';     this.width = this.canvas.width = this.config.width || +(computed.width.replace(/px/, ''));     this.height = this.canvas.height = this.config.height || +(computed.height.replace(/px/, ''));     this.canvas.style.cssText = 'position:absolute; top: 0px; left:0px';     container.appendChild(this.canvas);      var map = function(value, istart, istop, ostart, ostop) {        return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));     };      this.mapIntensityToColor = function(intensity, min, max) {        var cint = map(intensity, min, max, 0, 255);        /**        * Based On Rainbow Gradient        */        if (cint > 204) {           return [255, Math.round(map(intensity, min, max, 255, 0)), 0];        }         if (cint > 153) {           max = (203 / 255 * 100) * (max / 100);           return [Math.round(map(intensity, 0, max, 255, 0)), 255, 0];        }         if (cint > 102) {           max = (153 / 255 * 100) * (max / 100);           return [0, 255, Math.round(map(intensity, 0, max, 255, 0))];        }         if (cint > 0) {           max = (102 / 255 * 100) * (max / 100);           return [0, Math.round(map(intensity, 0, max, 255, 0)), 255];        }        max = (51 / 255 * 100) * (max / 100);        return [0, 0, Math.round(map(intensity, 0, max, 0, 255))];     };      this.draw = function(data) {       var min = 0;       var max = 1300;       var data = [         [0, 50, 1300],         [50, 100, 1100],         [100, 150, 1100],         [150, 200, 1000],         [200, 250, 500],         [250, 300, 400],         [300, 350, 300],         [350, 450, 200],         [450, 500, 400],         [500, 900, 0],         [900, 950, 300],         [950, 3350, 0]       ];       var point, startY, endY, alpha, val, color;       this.ctx.globalAlpha = 0.75;        for (var i = 0, l = data.length; i < l; i++) {         point = data[i];         startY = point[0];         endY = point[1];         val = point[2];         color = this.mapIntensityToColor(val, min, max);         this.ctx.fillStyle = "rgb(" + color.join(",") + ")";         this.ctx.fillRect(0, startY, this.width, endY - startY);     }  };}; var a = new Scroll({"container": "#overlay"}); a.draw(); 
#overlay {   width: 100%;   height: 2000px;   position: absolute;   top: 0px;   left: 0px; } 
<div id="overlay"></div> 

Output of above function

enter image description here

Expected Output

enter image description here

I tried using Linear gradient but the color blending is very poor.

Linear Gradient

https://jsfiddle.net/bdxeca48/2/

2 Answers

Answers 1

You could just use a linear gradient with a single color stop at the "middle" of each step:

this.draw = function(data) {     var min = 0;     var max = 1300;     var data = [         [0, 50, 1300],         [50, 100, 1100],         [100, 150, 1100],         [150, 200, 1000],         [200, 250, 500],         [250, 300, 400],         [300, 350, 300],         [350, 450, 200],         [450, 500, 400],         [500, 900, 0],         [900, 950, 300],         [950, 3350, 0]     ];      var point, startY, endY, alpha, val, color;     this.ctx.globalAlpha = 0.75;      // Calculate the maximum y scrolled     var maxScrollY = 0;     for(var i = 0, l = data.length; i < l; i++){         point = data[i];         if(maxScrollY < point[1]){             maxScrollY = point[1];         }     }     // here, maxScrollY will be 3350      var linearGrad = ctx.createLinearGradient(0, 0, 0, maxScrollY);      // Build the gradient     for (var i = 0, l = data.length; i < l; i++) {         point = data[i];          // You have to divide the coordinate by maxScrollY to get         // coordinates between 0.0 and 1.0         startY = point[0] / maxScrollY;         endY = point[1] / maxScrollY;          // Take the y coordinate between startY and endY for the color stop coordinate         var middleY = startY + (endY-startY)/2;          val = point[2];         color = this.mapIntensityToColor(val, min, max);         linearGrad.addColorStop(middleY, "rgb(" + color.join(",") + ")");     }      // Then just render     ctx.fillStyle = linearGrad;     ctx.fillRect(0, 0, this.width, maxScrollY); } 

Result: Result

Here is a demo: https://jsfiddle.net/4n294hb1/

Answers 2

Fiddle here: https://jsfiddle.net/Lfhdzw2c/

I replaced your IntensityToColor function with this, which I borrowed from https://rainbowcoding.com/how-to-create-rainbow-text-in-html-css-javascript/

function color_from_hue(hue) {   var h = hue/60;   var c = 255;   var x = (1 - Math.abs(h%2 - 1))*255;   var color;    var i = Math.floor(h);   if (i == 0) color = rgb_to_hex(c, x, 0);   else if (i == 1) color = rgb_to_hex(x, c, 0);   else if (i == 2) color = rgb_to_hex(0, c, x);   else if (i == 3) color = rgb_to_hex(0, x, c);   else if (i == 4) color = rgb_to_hex(x, 0, c);   else color = rgb_to_hex(c, 0, x);    return color; } 
Read More