I'm writing Visual WebPart for Sharepoint 2010, and I need use HTML5 canvas.
document.getElementById("testDiv").innerHTML = 'Right';
ctx = canvas.getContext("2d");
cxt.fillStyle="#000000;
cxt.fillRect(0,0,150,75);
But there is error:
Runtime error Microsoft JScript: Object does not support property or method "getContext"
When I try to use this code in ASP.NET web application< it's work fine. What's wrong?\
P.S: all code:
<!DOCTYPE HTML>
<style type="text/css">
.clocks {
height: 500px;
margin: 25px auto;
position: relative;
width: 500px;
}
var canvas;
var ctx;
var clockRadius = 250;
var clockImage;
// функции отрисовки :
function clear() { // очистка
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
function drawScene() { // основная функция drawScene
clear(); // очистка канвы
// получение текущего времени
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
hours = hours > 12 ? hours - 12 : hours;
var hour = hours + minutes / 60;
var minute = minutes + seconds / 60;
// сохранение
ctx.save();
// отрисовка часов (как бэк)
ctx.drawImage(clockImage, 0, 0, 500, 500);
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.beginPath();
// отрисовка чисел
ctx.font = '36px Arial';
ctx.fillStyle = '#000';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
for (var n = 1; n <= 12; n++) {
var theta = (n - 3) * (Math.PI * 2) / 12;
var x = clockRadius * 0.7 * Math.cos(theta);
var y = clockRadius * 0.7 * Math.sin(theta);
ctx.fillText(n, x, y);
}
// часы
ctx.save();
var theta = (hour - 3) * 2 * Math.PI / 12;
ctx.rotate(theta);
ctx.beginPath();
ctx.moveTo(-15, -5);
ctx.lineTo(-15, 5);
ctx.lineTo(clockRadius * 0.5, 1);
ctx.lineTo(clockRadius * 0.5, -1);
ctx.fill();
ctx.restore();
// минуты
ctx.save();
var theta = (minute - 15) * 2 * Math.PI / 60;
ctx.rotate(theta);
ctx.beginPath();
ctx.moveTo(-15, -4);
ctx.lineTo(-15, 4);
ctx.lineTo(clockRadius * 0.8, 1);
ctx.lineTo(clockRadius * 0.8, -1);
ctx.fill();
ctx.restore();
// секунды
ctx.save();
var theta = (seconds - 15) * 2 * Math.PI / 60;
ctx.rotate(theta);
ctx.beginPath();
ctx.moveTo(-15, -3);
ctx.lineTo(-15, 3);
ctx.lineTo(clockRadius * 0.9, 1);
ctx.lineTo(clockRadius * 0.9, -1);
ctx.fillStyle = '#0f0';
ctx.fill();
ctx.restore();
ctx.restore();
}
function init() {
canvas = document.getElementById("canvas");
if (canvas.getContext) {
document.getElementById("testDiv").innerHTML = 'Right';
ctx = canvas.getContext("2d");
clockImage = new Image();
// setInterval(drawScene, 1000);
cxt.fillStyle="Red";
cxt.fillRect(0,0,150,75);
}
else {
ctx = canvas.getContext("2d");
cxt.fillStyle="Green";
cxt.fillRect(0,0,150,75);
document.getElementById("testDiv").innerHTML = 'Error';
}
}
// инициализация
window.onload = init;
</script>
<div class="clocks">
<canvas id="canvas" width="500" height="500">
</canvas>
The browser you are using does not seem to support the <canvas> element. The error you posted just shows that the object (canvas) doesn't support the method getContext.
See this post which explains how to check whether your browser supports canvas. Actually the answer contains exactly the code you are trying to use to detect whether canvas is supported - seems in your case canvas is not supprted:
function isCanvasSupported(){
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
}
ctx = canvas.getContext("2d");
cxt.fillStyle="#000000;
ctx and cxt =)
right
ctx.fillStyle="#000000;
Related
I followed a tutorial for building a JS analogue clock and now I'd like to create an identical second clock on the page to experiment with.
When I've tried adding a second clock it overwrites the first clock - I believe this is because the variables ctx and radius are set globally.
Working example:
var canvas = document.getElementById("cambs_clock");
var ctx = canvas.getContext("2d");
var radius = canvas.height / 2;
ctx.translate(radius, radius);
radius = radius * 0.90;
//drawClock();
setInterval(drawClock, 1000);
function drawClock()
{
drawFace(ctx, radius);
drawNumbers(ctx, radius);
drawTime(ctx, radius);
}
I tried turning the block of code that generates the ctx and radius variables into a function and adding params to the drawClock function but that resulted in no clocks being drawn whatsoever:
function setupClock(clock)
{
var canvas = document.getElementById("cambs_clock");
var ctx = canvas.getContext("2d");
var radius = canvas.height / 2;
ctx.translate(radius, radius);
radius = radius * 0.90;
setInterval(drawClock(ctx, radius), 1000);
}
//drawClock();
//setInterval(drawClock, 1000);
setupClock();
function drawClock(ctx,radius)
{
drawFace(ctx, radius);
drawNumbers(ctx, radius);
drawTime(ctx, radius);
}
function drawFace(ctx, radius) {
var grad;
ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
grad = ctx.createRadialGradient(0, 0 ,radius * 0.95, 0, 0, radius * 1.05);
grad.addColorStop(0, '#333');
grad.addColorStop(0.5, 'black');
grad.addColorStop(1, '#333');
ctx.strokeStyle = grad;
ctx.lineWidth = radius*0.05;
ctx.stroke();
ctx.beginPath();
ctx.arc(0, 0, radius * 0.1, 0, 2 * Math.PI);
ctx.fillStyle = '#333';
ctx.fill();
}
function drawNumbers(ctx, radius) {
var ang;
var num;
ctx.font = radius * 0.15 + "px arial";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
for(num = 1; num < 13; num++){
ang = num * Math.PI / 6;
ctx.rotate(ang);
ctx.translate(0, -radius * 0.85);
ctx.rotate(-ang);
ctx.fillText(num.toString(), 0, 0);
ctx.rotate(ang);
ctx.translate(0, radius * 0.85);
ctx.rotate(-ang);
}
}
function drawTime(ctx, radius){
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
//hour
hour = hour%12;
hour = (hour*Math.PI/6)+(minute*Math.PI/(6*60))+(second*Math.PI/(360*60));
drawHand(ctx, hour, radius*0.5, radius*0.07);
//minute
minute = (minute*Math.PI/30)+(second*Math.PI/(30*60));
drawHand(ctx, minute, radius*0.8, radius*0.07);
// second
second = (second*Math.PI/30);
drawHand(ctx, second, radius*0.9, radius*0.02);
}
function drawHand(ctx, pos, length, width) {
ctx.beginPath();
ctx.lineWidth = width;
ctx.lineCap = "round";
ctx.moveTo(0,0);
ctx.rotate(pos);
ctx.lineTo(0, -length);
ctx.stroke();
ctx.rotate(-pos);
}
</script>
The above code results in no clocks being drawn.
How would I be able to expand this code to accommodate multiple clocks?
(The end game is to have several clocks for different timezones in case that makes a difference)
You have tried the following:
function setupClock(clock)
{
var canvas = document.getElementById("cambs_clock");
var ctx = canvas.getContext("2d");
var radius = canvas.height / 2;
ctx.translate(radius, radius);
radius = radius * 0.90;
setInterval(() => drawClock(ctx, radius), 1000);
}
setupClock();
Notice that that function has an argument, clock which is not used. Furthermore, with document.getElementById("cambs_clock"); you always target the same canvas. So what you need in your case are two canvas's like
<canvas id="clock1"></canvas>
<canvas id="clock2"></canvas>
And the following script
function setupClock(clock)
{
var canvas = document.getElementById(clock);
var ctx = canvas.getContext("2d");
var radius = canvas.height / 2;
ctx.translate(radius, radius);
radius = radius * 0.90;
setInterval(drawClock(ctx, radius), 1000);
}
setupClock('clock1');
setupClock('clock2');
You can pass the radius as well as an argument if you like:
function setupClock(clock, radius) { ... }
setupClock('clock2', 20);
Endless possibilities, good luck!
Change
setInterval(drawClock(ctx, radius), 1000);
to
setInterval(() => {
drawClock(ctx, radius);
}, 1000);
I am experiencing trouble in rotating a circle with HTML5 canvas.
the function is about control a circle,
but the scale is out of control...
anyone know how to adjust(or set rotate) the scale to fit the canvas circle?
The starting angle(0.7 pi) and endAngle(0.3 pi).
Do I need to reset the rotate?
--> ctx.rotate(Math.PI * 3 / 16);
-->(math.pi*15/10*1/8)
var degrees = 0;
var color = "lightblue";
var bgcolor = "#222";
var canvas, ctx, W, Htext;
function init_rpm(name, val) {
canvas = document.getElementById(name);
ctx = canvas.getContext("2d");
//dimensions
W = canvas.width;
H = canvas.height;
//Clear the canvas everytime a chart is drawn
ctx.clearRect(0, 0, W, H);
//Background 360 degree arc
ctx.beginPath();
ctx.lineWidth = 25;
ctx.strokeStyle = bgcolor;
ctx.arc(W / 2, H / 2, Math.floor(W / 3), 0.7 * Math.PI, 0.3 * Math.PI, false); //you can see thr src now
ctx.stroke();
//center circle
ctx.save();
ctx.beginPath();
ctx.strokeStyle = 'rgba(255, 255, 255, .2)';
ctx.lineWidth = 10;
ctx.arc(W / 2, H / 2, Math.floor(W / 3) - 40, 0.7 * Math.PI, 0.3 * Math.PI, false);
ctx.stroke();
ctx.restore();
// scale
ctx.save();
ctx.translate(300, 300);
for (var i = 0; i < 9; i++) {
ctx.beginPath();
ctx.lineWidth = 2;
ctx.strokeStyle = 'rgba(255, 255, 255, .3)';
ctx.moveTo(130, 0);
ctx.lineTo(140, 0);
ctx.stroke();
ctx.rotate(Math.PI * 3 / 16);
}
ctx.restore();
//angle in radians =angle in drgrees*pi/180 make color
var percent = val / 8000 * 100;
ctx.beginPath();
ctx.lineWidth = 30;
// ctx.strokeStyle= color;
var my_gradient = ctx.createLinearGradient(0, 150, 250, 300);
my_gradient.addColorStop(0, "#B31918");
my_gradient.addColorStop(1, "#FFA000");
ctx.strokeStyle = my_gradient;
//the arc start from the rightmost end. if we deduct 90 degrees from the angles
//the arc will start from the top most end
ctx.arc(W / 2, H / 2, Math.floor(W / 3), 0.7 * Math.PI, 0.7 * Math.PI + 1.6 * Math.PI / 100 * percent, false); //you can see thr src now
ctx.stroke();
//add text
ctx.fillStyle = color;
ctx.font = "7vh play";
// text=Math.floor(degrees/360*8)+' RPM';
text = degrees / 360 * 8;
text_width = ctx.measureText(text).width;
ctx.fillText(text, W / 2 - text_width / 2, H / 2 + 15);
ctx.font = "3vh play";
text2 = 'RPM';
ctx.fillText(text2, W / 2 - text_width / 2, H / 2 + 70);
}
function draw(val, name, type) {
// console.log(val);
if (name != "" || name != null) {
if (type == "rpm") {
if (val != "" || val != null) {
degrees = val / 1000 / 8 * 360;
} else {
degrees = 180;
}
init_rpm(name, val);
} else if (type == "kmh") {
if (val != "" || val != null) {
degrees = val;
} else {
degrees = 180;
}
init_kmh(name);
}
} else {
console.log('can not find canvas id');
}
}
$(document).ready(function () {
//canvas init
draw(0, "canvas3", "rpm");
var rpmControl2 = document.querySelector('input[id=get_rpm]');
rpmControl2.addEventListener('input', function () {
draw(this.value, "canvas3", "rpm");
});
});
#canvas2{
display:inline;
}
body{
background:#333;
font-family: 'Play', sans-serif;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div class="container-fluid">
<input id="get_rpm" type="number" value="0" min="0" max="8000" step="100" />
<span style="color:white">RPM</span>
<canvas id="canvas3" width="600" height="600"></canvas>
Your scale is drawn by drawing its lines in a single direction and then controlling the context's rotation to make all these lines point at a different angle.
Just like if you held a ruler always in the same direction and simply rotated the leaf of paper underneath.
So to control the rotation of your scale, you have to set the context's rotation (or leaf of paper) before you draw the first line.
var ctx = c.getContext('2d');
angle.oninput = function(e) {
ctx.clearRect(0, 0, c.width, c.height);
var rad = angle.value * (Math.PI / 180);
// move the context so its center be at 0,0
ctx.setTransform(1, 0, 0, 1, c.width/2, c.height/2);
// rotate it so we face the required angle
ctx.rotate(rad);
var stepAngle = Math.PI*2 / 14,
innerRad = c.width / 2.8,
outerRad = c.width / 2.5;
ctx.beginPath();
for(var i = 0; i < 12; i++) {
ctx.moveTo(0, innerRad); // move vertically
ctx.lineTo(0, outerRad); // draw line vertically
ctx.rotate(stepAngle); // rotate by fixed increment
}
ctx.stroke(); // all drawn, we can stroke
ctx.setTransform(1, 0, 0, 1, 0, 0); // reset context's position
};
angle.oninput();
<input type="range" min="0" max="360" id="angle"><br>
<canvas id="c" width="200" height="200"></canvas>
And with your code:
var degrees = 0;
var color = "lightblue";
var bgcolor = "#222";
var canvas, ctx, W, Htext;
function init_rpm(name, val) {
canvas = document.getElementById(name);
ctx = canvas.getContext("2d");
//dimensions
W = canvas.width;
H = canvas.height;
//Clear the canvas everytime a chart is drawn
ctx.clearRect(0, 0, W, H);
//Background 360 degree arc
ctx.beginPath();
ctx.lineWidth = 25;
ctx.strokeStyle = bgcolor;
ctx.arc(W / 2, H / 2, Math.floor(W / 3), 0.7 * Math.PI, 0.3 * Math.PI, false); //you can see thr src now
ctx.stroke();
//center circle
ctx.beginPath();
ctx.strokeStyle = 'rgba(255, 255, 255, .2)';
ctx.lineWidth = 10;
ctx.arc(W / 2, H / 2, Math.floor(W / 3) - 40, 0.7 * Math.PI, 0.3 * Math.PI, false);
ctx.stroke();
//EDITS BEGIN HERE
// scale
ctx.setTransform(1, 0, 0, 1, 300, 300);
ctx.beginPath();
ctx.lineWidth = 2;
ctx.strokeStyle = 'rgba(255, 255, 255, .3)';
// there should be 10 lines
var stepAngle = (Math.PI * 2) / 10;
// begin angle
ctx.rotate(0.7 * Math.PI);
// draw only 9 of the 10 lines
for (var i = 0; i < 9; i++) {
ctx.moveTo(130, 0);
ctx.lineTo(140, 0);
ctx.rotate(stepAngle);
}
ctx.stroke();
ctx.setTransform(1, 0, 0, 1, 0, 0);
//EDITS END HERE
var percent = val / 8000 * 100;
ctx.beginPath();
ctx.lineWidth = 30;
var my_gradient = ctx.createLinearGradient(0, 150, 250, 300);
my_gradient.addColorStop(0, "#B31918");
my_gradient.addColorStop(1, "#FFA000");
ctx.strokeStyle = my_gradient;
//the arc start from the rightmost end. if we deduct 90 degrees from the angles
//the arc will start from the top most end
ctx.arc(W / 2, H / 2, Math.floor(W / 3), 0.7 * Math.PI, 0.7 * Math.PI + 1.6 * Math.PI / 100 * percent, false); //you can see thr src now
ctx.stroke();
//add text
ctx.fillStyle = color;
ctx.font = "7vh play";
// text=Math.floor(degrees/360*8)+' RPM';
text = degrees / 360 * 8;
text_width = ctx.measureText(text).width;
ctx.fillText(text, W / 2 - text_width / 2, H / 2 + 15);
ctx.font = "3vh play";
text2 = 'RPM';
ctx.fillText(text2, W / 2 - text_width / 2, H / 2 + 70);
}
function draw(val, name, type) {
// console.log(val);
if (name != "" || name != null) {
if (type == "rpm") {
if (val != "" || val != null) {
degrees = val / 1000 / 8 * 360;
} else {
degrees = 180;
}
init_rpm(name, val);
} else if (type == "kmh") {
if (val != "" || val != null) {
degrees = val;
} else {
degrees = 180;
}
init_kmh(name);
}
} else {
console.log('can not find canvas id');
}
}
$(document).ready(function () {
//canvas init
draw(0, "canvas3", "rpm");
var rpmControl2 = document.querySelector('input[id=get_rpm]');
rpmControl2.addEventListener('input', function () {
draw(this.value, "canvas3", "rpm");
});
});
#canvas2{
display:inline;
}
body{
background:#333;
font-family: 'Play', sans-serif;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div class="container-fluid">
<input id="get_rpm" type="number" value="0" min="0" max="8000" step="100" />
<span style="color:white">RPM</span>
<canvas id="canvas3" width="600" height="600"></canvas>
clock digit display incorrect position how to rotate correct position .
I think does not colculate correct angle of each digit.
these lines of code have error and here is calculate angle of each digit
any one finde the error and how to solve this
and how to calculate analog clock wise digit
for (var n = 1; n <=12; n++) {
var theta = (n - 12) * (Math.PI * 2) / 12;
var x = clockRadius * 0.7 * Math.cos(theta);
var y = clockRadius * 0.7 * Math.sin(theta);
ctx.fillText(n, x, y);
ctx.rotate(theta);
}
clock image here
clock clocke
<canvas id="canvas" width="150" height="150"></canvas>
<script>
function init(){
clock();
setInterval(clock, 1000);
}
function toRad(degrees) {
return degrees * (Math.PI / 180);
}
function clock(){
var ctx = document.getElementById('canvas').getContext('2d');
var clockRadius = 110;
ctx.save();
ctx.clearRect(0,0,150,150);
ctx.translate(75,75);
ctx.scale(0.4,0.4);
ctx.rotate(-Math.PI/2);
ctx.fillStyle = "white";
ctx.lineWidth = 8;
ctx.lineCap = "round";
ctx.font = '22px Helvetica,Arial,sans-serif';
ctx.fillStyle = '#fff';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
var now = new Date($("#datetime").val());
//alert(now);
var sec = now.getSeconds();
var min = now.getMinutes();
var hr = now.getHours();
hr = hr>=12 ? hr-12 : hr;
for (var n = 1; n <=12; n++) {
var theta = (n - 12) * (Math.PI * 2) / 12;
var x = clockRadius * 0.7 * Math.cos(theta);
var y = clockRadius * 0.7 * Math.sin(theta);
ctx.fillText(n, x, y);
ctx.rotate(theta );
}
ctx.strokeStyle = "white";
ctx.save();
for (var i=0; i < 12; i++){
ctx.beginPath();
ctx.rotate(Math.PI/6);
ctx.moveTo(100,0);
ctx.lineTo(120,0);
ctx.stroke();
}
ctx.restore();
// Minute marks
ctx.save();
ctx.lineWidth = 5;
for (i=0;i<60;i++){
if (i%5!=0) {
ctx.beginPath();
ctx.moveTo(117,0);
ctx.lineTo(120,0);
ctx.stroke();
}
ctx.rotate(Math.PI/30);
}
ctx.restore();
ctx.fillStyle = "black";
// write Hours
ctx.strokeStyle = "#4D514E";
ctx.save();
ctx.rotate( hr*(Math.PI/6) + (Math.PI/360)*min + (Math.PI/21600)*sec )
ctx.lineWidth = 14;
ctx.beginPath();
ctx.moveTo(-20,0);
ctx.lineTo(80,0);
ctx.stroke();
ctx.restore();
// write Minutes
ctx.save();
ctx.rotate( (Math.PI/30)*min + (Math.PI/1800)*sec )
ctx.lineWidth = 10;
ctx.beginPath();
ctx.moveTo(-28,0);
ctx.lineTo(110,0);
ctx.stroke();
ctx.restore();
// Write seconds
ctx.save();
ctx.rotate(sec * Math.PI/30);
ctx.strokeStyle = "#D40000";
ctx.fillStyle = "#D40000";
ctx.lineWidth = 6;
ctx.beginPath();
ctx.moveTo(-30,0);
ctx.lineTo(110,0);
ctx.stroke();
ctx.beginPath();
ctx.arc(0,0,10,0,Math.PI*2,true);
ctx.fill();
ctx.beginPath();
ctx.arc(0,0,10,0,Math.PI*2,true);
ctx.stroke();
ctx.fillStyle = "rgba(0,0,0,0)";
ctx.arc(0,0,3,0,Math.PI*2,true);
ctx.fill();
ctx.restore();
ctx.beginPath();
ctx.lineWidth = 14;
ctx.strokeStyle = '#494545';
ctx.arc(0,0,142,0,Math.PI*2,true);
ctx.stroke();
ctx.restore();
} init();
</script>
You rotate the whole context in the line 7 of the clock function.
function clock(){
var ctx = document.getElementById('canvas').getContext('2d');
var clockRadius = 110;
ctx.save();
ctx.clearRect(0,0,150,150);
ctx.translate(75,75);
ctx.scale(0.4,0.4);
ctx.rotate(-Math.PI/2); // <-- remove this
ctx.fillStyle = "white";
...
You need to remove that. Instead of doing that you can just rotate when drawing the arms.
// write Hours
ctx.rotate( -Math.PI/2 + hr*(Math.PI/6) + (Math.PI/360)*min + (Math.PI/21600)*sec )
// write Minutes
ctx.rotate( -Math.PI/2 + (Math.PI/30)*min + (Math.PI/1800)*sec )
// Write seconds
ctx.rotate( -Math.PI/2 + sec * Math.PI/30);
(and the codes for drawing digits will need a minor fix)
var theta = (n - 3) * (Math.PI * 2) / 12;
function init(){
clock();
setInterval(clock, 1000);
}
function toRad(degrees) {
return degrees * (Math.PI / 180);
}
function clock(){
var ctx = document.getElementById('canvas').getContext('2d');
var clockRadius = 110;
ctx.save();
ctx.clearRect(0,0,150,150);
ctx.translate(75,75);
ctx.scale(0.4,0.4);
ctx.fillStyle = "white";
ctx.lineWidth = 8;
ctx.lineCap = "round";
ctx.font = '22px Helvetica,Arial,sans-serif';
ctx.fillStyle = '#fff';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
var now = new Date('2000/1/1 ' + $("#datetime").val());
//alert(now);
var sec = now.getSeconds();
var min = now.getMinutes();
var hr = now.getHours();
hr = hr>=12 ? hr-12 : hr;
for (var n = 1; n <=12; n++) {
var theta = (n - 3) * (Math.PI * 2) / 12;
var x = clockRadius * 0.7 * Math.cos(theta);
var y = clockRadius * 0.7 * Math.sin(theta);
ctx.fillText(n, x, y);
}
ctx.strokeStyle = "white";
ctx.save();
for (var i=0; i < 12; i++){
ctx.beginPath();
ctx.rotate(Math.PI/6);
ctx.moveTo(100,0);
ctx.lineTo(120,0);
ctx.stroke();
}
ctx.restore();
// Minute marks
ctx.save();
ctx.lineWidth = 5;
for (i=0;i<60;i++){
if (i%5!=0) {
ctx.beginPath();
ctx.moveTo(117,0);
ctx.lineTo(120,0);
ctx.stroke();
}
ctx.rotate(Math.PI/30);
}
ctx.restore();
ctx.fillStyle = "black";
// write Hours
ctx.strokeStyle = "#4D514E";
ctx.save();
ctx.rotate( -Math.PI/2 + hr*(Math.PI/6) + (Math.PI/360)*min + (Math.PI/21600)*sec )
ctx.lineWidth = 14;
ctx.beginPath();
ctx.moveTo(-20,0);
ctx.lineTo(80,0);
ctx.stroke();
ctx.restore();
// write Minutes
ctx.save();
ctx.rotate( -Math.PI/2 +(Math.PI/30)*min + (Math.PI/1800)*sec )
ctx.lineWidth = 10;
ctx.beginPath();
ctx.moveTo(-28,0);
ctx.lineTo(110,0);
ctx.stroke();
ctx.restore();
// Write seconds
ctx.save();
ctx.rotate(-Math.PI/2 +sec * Math.PI/30);
ctx.strokeStyle = "#D40000";
ctx.fillStyle = "#D40000";
ctx.lineWidth = 6;
ctx.beginPath();
ctx.moveTo(-30,0);
ctx.lineTo(110,0);
ctx.stroke();
ctx.beginPath();
ctx.arc(0,0,10,0,Math.PI*2,true);
ctx.fill();
ctx.beginPath();
ctx.arc(0,0,10,0,Math.PI*2,true);
ctx.stroke();
ctx.fillStyle = "rgba(0,0,0,0)";
ctx.arc(0,0,3,0,Math.PI*2,true);
ctx.fill();
ctx.restore();
ctx.beginPath();
ctx.lineWidth = 14;
ctx.strokeStyle = '#494545';
ctx.arc(0,0,142,0,Math.PI*2,true);
ctx.stroke();
ctx.restore();
} init();
canvas {
background: blue;
}
<input type="time" id="datetime" value="03:45:01">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="150" height="150"></canvas>
<script>
</script>
Since you call ctx.rotate(-Math.PI/2) at the beginning of your clock function, you need to rotate the digits back. To do this you'd need to translate context to a digit coordinates first, and then rotate the context by Math.PI/2.
Replace this part of code in your for loop:
ctx.fillText(n, x, y);
ctx.rotate(theta );
with this:
ctx.save();
ctx.translate(x, y);
ctx.rotate(Math.PI/2);
ctx.fillText(n, 0, 0);
ctx.restore();
I have 2 canvasses that visualize values from 2 different labels.
I wrote 2 almost the same javascripts and when I run my application. It skips the first visualitation and only shows the second one. Where is my mistake?
Here is my html code:-
<div><canvas id="canvas" width="300" height="300"></canvas></div>
<asp:Label ID="LblGauge" runat="server"></asp:Label>
<div><canvas id="canvas2" width="300" height="300"></canvas></div>
<asp:Label ID="LblGauge1" runat="server"></asp:Label>
And here are my 2 javascripts. The only difference now is the canvas/canvas2 and the lblgauge and lblgauge1. Even if I change all the variables in the second script it will still only show the second visualition.
<script>
window.onload = function () {
//canvas initialization
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//dimensions
var W = canvas.width;
var H = canvas.height;
//Variables
var degrees = document.getElementById("LblGauge").textContent;
var new_degrees = 0;
var difference = 0;
var color = "lightgreen";
var bgcolor = "#222";
var text;
var animation_loop, redraw_loop;
function init() {
//Clear the canvas everytime a chart is drawn
ctx.clearRect(0, 0, W, H);
//Background 360 degree arc
ctx.beginPath();
ctx.strokeStyle = bgcolor;
ctx.lineWidth = 30;
ctx.arc(W / 2, H / 2, 100, 0, Math.PI * 2, false);
ctx.stroke();
//Angle in radians = angle in degrees * PI / 180
var radians = degrees * Math.PI / 180;
ctx.beginPath();
ctx.strokeStyle = color;
ctx.lineWidth = 30;
//the arc will start from the topmost end
ctx.arc(W / 2, H / 2, 100, 0 - 90 * Math.PI / 180, radians - 90 * Math.PI / 180, false);
ctx.stroke();
//Lets add the text
ctx.fillStyle = color;
ctx.font = "50px bebas";
text = Math.floor(degrees / 360 * 100) + "%";
text_width = ctx.measureText(text).width;
ctx.fillText(text, W / 2 - text_width / 2, H / 2 + 15);
}
function draw() {
//Cancel any movement animation if a new chart is requested
if (typeof animation_loop != undefined) clearInterval(animation_loop);
////time for each frame is 1sec / difference in degrees
animation_loop = setInterval(animate_to, 1000 / difference);
}
//function to make the chart move to new degrees
function animate_to() {
if (degrees == new_degrees)
if (degrees < new_degrees)
degrees++;
else
degrees--;
init();
}
draw();
}
</script>
<script>
window.onload = function () {
//canvas initialization
var canvas = document.getElementById("canvas2");
var ctx = canvas.getContext("2d");
//dimensions
var W = canvas.width;
var H = canvas.height;
//Variables
var degrees = document.getElementById("LblGauge1").textContent;
var new_degrees = 0;
var difference = 0;
var color = "lightgreen";
var bgcolor = "#222";
var text;
var animation_loop, redraw_loop;
function init() {
//Clear the canvas everytime a chart is drawn
ctx.clearRect(0, 0, W, H);
//Background 360 degree arc
ctx.beginPath();
ctx.strokeStyle = bgcolor;
ctx.lineWidth = 30;
ctx.arc(W / 2, H / 2, 100, 0, Math.PI * 2, false);
ctx.stroke();
//Angle in radians = angle in degrees * PI / 180
var radians = degrees * Math.PI / 180;
ctx.beginPath();
ctx.strokeStyle = color;
ctx.lineWidth = 30;
//the arc will start from the topmost end
ctx.arc(W / 2, H / 2, 100, 0 - 90 * Math.PI / 180, radians - 90 * Math.PI / 180, false);
ctx.stroke();
//Lets add the text
ctx.fillStyle = color;
ctx.font = "50px bebas";
text = Math.floor(degrees / 360 * 100) + "%";
text_width = ctx.measureText(text).width;
ctx.fillText(text, W / 2 - text_width / 2, H / 2 + 15);
}
function draw() {
//Cancel any movement animation if a new chart is requested
if (typeof animation_loop != undefined) clearInterval(animation_loop);
////time for each frame is 1sec / difference in degrees
animation_loop = setInterval(animate_to, 1000 / difference);
}
//function to make the chart move to new degrees
function animate_to() {
if (degrees == new_degrees)
if (degrees < new_degrees)
degrees++;
else
degrees--;
init();
}
draw();
}
</script>
Can somebody tell me how to change my code.
This is what the javascript shows me when it works.
I'm drawing lines with a pattern i'm creating on different canvas.
I'm translating and scaling the context matrices and creating another pattern to achieve that each line will start exactly from the beginning of the pattern. (as we know that patterns are created from the beginning of the context repeatedly for all context area and not depends on the drawing)
I've managed to do so as show below for most of the cases.
Each row represents a scale. and drawing many lines on different Y values.
Each line should have red circles repeatedly along the X axis. It is working for many scales.
The problem is in scale 1.6. The 3rd row lines. As we see, the lines in this row are not well patterned as the Y value is growing, and also the start is not right.
I think it is some floating point problem.. but i can't find the problem.
var ctx = demo.getContext('2d'),
pattern,
offset = 0;
/// create main pattern
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(8, 8, 7, 0, Math.PI * 2);
ctx.fill();
runScale(1, 0);
runScale(1.5, 120);
runScale(1.6, 240);
runScale(2, 360);
runScale(3, 480);
function runScale(scale, firstPntX) {
var newCanvasSize = {
width: demo.width * scale,
height: demo.height * scale
};
demo2.width = Math.round(newCanvasSize.width);
demo2.height = Math.round(newCanvasSize.height);
var firstPnt = {
x: firstPntX
};
var offsetPnt = {
x: 0,
y: (newCanvasSize.height / 2)
};
var ctx2 = demo2.getContext('2d');
var pt = ctx2.createPattern(demo, 'repeat');
ctx = demo3.getContext('2d');
for (var i = 20; i < 1000; i += (demo2.height + 10)) {
drawLines(i);
}
function drawLines(y) {
firstPnt.y = y;
demo2.width = demo2.width;
ctx2.fillStyle = pt;
var offsets = [firstPnt.x, y - demo2.height / 2];
ctx2.translate(offsets[0], offsets[1]);
ctx2.scale(scale, scale);
ctx2.fillRect(-offsets[0] / scale, -offsets[1] / scale, demo2.width / scale, demo2.height / scale);
ctx.lineWidth = newCanvasSize.height;
pattern = ctx.createPattern(demo2, 'repeat');
ctx.beginPath();
ctx.moveTo(firstPnt.x, firstPnt.y);
ctx.lineTo(firstPnt.x + 100, firstPnt.y);
ctx.strokeStyle = 'lightgreen';
ctx.stroke();
ctx.strokeStyle = pattern;
ctx.stroke();
}
}
canvas {
border: 1px solid #000
}
<canvas id="demo" width=16 height=16></canvas>
<canvas id="demo2"></canvas>
<canvas id="demo3" width=600 height=400></canvas>
After struggling all day with this problem i finally decided to post this question here.
And now, an hour later I've found the solution by myself..
I've decided not to delete it for the sake of the forum.
The solution is simply change the offsets.
Change this line
var offsets = [firstPnt.x, y - demo2.height / 2];
to this line
var offsets = [firstPnt.x % demo2.width,firstPnt.y % demo2.height - demo2.height / 2];
var ctx = demo.getContext('2d'),
pattern,
offset = 0;
/// create main pattern
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(8, 8, 7, 0, Math.PI * 2);
ctx.fill();
runScale(1, 0);
runScale(1.5, 120);
runScale(1.6, 240);
runScale(2, 360);
runScale(3, 480);
function runScale(scale, firstPntX) {
var newCanvasSize = {
width: demo.width * scale,
height: demo.height * scale
};
demo2.width = Math.round(newCanvasSize.width);
demo2.height = Math.round(newCanvasSize.height);
var firstPnt = {
x: firstPntX
};
var offsetPnt = {
x: 0,
y: (newCanvasSize.height / 2)
};
var ctx2 = demo2.getContext('2d');
var pt = ctx2.createPattern(demo, 'repeat');
ctx = demo3.getContext('2d');
for (var i = 20; i < 1000; i += (demo2.height + 10)) {
drawLines(i);
}
function drawLines(y) {
firstPnt.y = y;
demo2.width = demo2.width;
ctx2.fillStyle = pt;
var offsets = [firstPnt.x % demo2.width, firstPnt.y % demo2.height - demo2.height / 2];
ctx2.translate(offsets[0], offsets[1]);
ctx2.scale(scale, scale);
ctx2.fillRect(-offsets[0] / scale, -offsets[1] / scale, demo2.width / scale, demo2.height / scale);
ctx.lineWidth = newCanvasSize.height;
pattern = ctx.createPattern(demo2, 'repeat');
ctx.beginPath();
ctx.moveTo(firstPnt.x, firstPnt.y);
ctx.lineTo(firstPnt.x + 100, firstPnt.y);
ctx.strokeStyle = 'lightgreen';
ctx.stroke();
ctx.strokeStyle = pattern;
ctx.stroke();
}
}
canvas {
border: 1px solid #000
}
<canvas id="demo" width=16 height=16></canvas>
<canvas id="demo2"></canvas>
<canvas id="demo3" width=600 height=400></canvas>
Thanks for reading :D