Results 1 to 2 of 2

Thread: Canvas Issue

  1. #1
    Join Date
    May 2014

    Canvas Issue


    I have been working with plotting mathematical functions on a canvas. I have, however, encountered an issue: when using coloured rectangles to plot points, the context.fillStyle property refuses to render certain functions properly. Other mathematical operations seem to work well.

    My source:

    var canvas = document.getElementById('my_canvas');
    if (canvas.getContext){
    var context = canvas.getContext('2d');
    for(var i=0; i<10; i++){
    a = Math.abs(50*Math.cos(i));
    context.fillStyle = "rgb(200, " + a + ", 0)";
    context.fillRect ((131+50*Math.sin(i)), (150+50*Math.cos(i)), 100, 100);

    As you can see, my function Math.abs(50*Math.cos(i)) is stored in variable a, and is concatenated into the fillStyle. What should happen is that the resulting rectangles should change colour as i increases. However, this is not the case. When a is set to certain functions, like 10*i or 10*(i^2), the program runs fine, and the blocks are coloured properly with respect to the value of a given i. Other times, when a is set to certain functions like Math.cos(i) or i^2, the blocks return all the same colour, without any change with respect to i. This error happens without reason or rhyme, and the functions causing this error share no obvious similarities.

    Note that the functions found in the fillRect() method work without problem regardless of the function entered. Only the function within fillStyle is error enountered.

    I have tried dozens of functions, and have searched Google for any hint as to the origin of this error. Nada. There seems to be no reports of this kind of error occurring. I use FireFox 29.0.1 on Windows Vista.

    Thanks in advance for any solution. Good Day.

  2. #2
    Math.floor your color. You can't have fractional color components in CSS. 0..255 INTEGER, not float. Canvas' fillStyle is effectively a CSS property, which is why it follows the same rules.

    a = Math.floor(Math.abs(50*Math.cos(i)));

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center