Fred Turner
Fred Turner

Reputation: 139

Change color of line segment in HTML5 Canvas with jQuery Colorpicker plugin

I have a HTML5 canvas with a several line segments on it. I want to add a jQuery color picker so I can let users change the stroke color of those segments. How do I get the value from the colorpicker to apply to a specific line segment?

edit...okay i have gotten it this far lol, but I can't figure out how to get the line to pick up the new myPicker

<script type="text/javascript" src="jscolor.js"></script>

<script type="text/javascript">
var myPicker = new jscolor.color(document.getElementById('myField1'), {})
</script>

<script type="application/javascript" language="javascript">
window.onload = function(){
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
    var myStroke = "#ff0000";

    context.moveTo(100, 150);
    context.lineTo(450, 150);
    context.lineWidth = 10;
    context.strokeStyle = myStroke;
    context.stroke();
};
</script>

Upvotes: 0

Views: 2572

Answers (1)

Josh1billion
Josh1billion

Reputation: 14927

Haven't tested it, but this should work:

$('#yourColorpickerField').ColorPicker({
onChange: function(hsb, hex, rgb, el) {
    var newColor = $(el).val(hex);

    var context = canvas.getContext('yourCanvasName');
    context.fillStyle = newColor;
    // here, you can draw your line again, or if you're already doing it on an interval, it should be fine for the next time you call it
}
});

That assumes your lines are all the same color. I see that you want this to apply to only a "specific line segment," in which case you'll need to modify the above code. It'll depend heavily upon what your existing code looks like, but basically, instead of setting context.fillStyle to the new color, you'll want to store the new color value in another variable that you can read later when it comes time to draw that particular line segment (at which point you'll set context.filleStyle to the color immediately before drawing the line).

Upvotes: 1

Related Questions